查找匹配行的第 N 次出现 [英] Finding the N th Occurrence of a Match line

查看:51
本文介绍了查找匹配行的第 N 次出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个行数相同的列表(多行文本字符串)(项目的顺序可能在很多方面不同,但行数可能不同):

I have list (multiline text string) with same number of line (order of items may differ in many ways and numbers of line may be however):

Ardei
Mere
Pere
Ardei
Castraveti

我想找到 第 2 次 匹配行包含Ardei"并将项目名称替换为另一个名称,并分别在另一个正则表达式中找到strong>1 st 出现 'Ardei' 并将名称替换为其他内容 (perl).

I want to find 2 th occurrence of a match line that contain 'Ardei' and replace name of item with another name and, separately in another regex, find 1 st occurrence of 'Ardei' and replace name with something else (perl).

推荐答案

假设您想将第 2 个nd "Ardei" 替换为 "XYZ".你可以这样做(PCRE 语法):

Let's say you want to replace the 2nd "Ardei" with "XYZ". You could do that like this (PCRE syntax):

^(?s)(.*?Ardei.*?)Ardei

并将其替换为:

$1XYZ

$1 包含在 (.*?Ardei.*?) 中捕获的所有内容,(?s) 将导致. 真正匹配每个字符(也包括换行符).

The $1 contains everything that is captured in (.*?Ardei.*?) and the (?s) will cause the . to match really every character (also line break chars).

一个小演示:

#!/usr/bin/perl -w

my $text = 'Ardei
Mere
Pere
Ardei
Castraveti
Ardei';

$text =~ s/^(?s)(.*?Ardei.*?)Ardei/$1XYZ/; 
# or just: $text =~ s/^(.*?Ardei.*?)Ardei/$1XYZ/s; 

print $text;

将打印:

Ardei
Mere
Pere
XYZ
Castraveti
Ardei

这篇关于查找匹配行的第 N 次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆