开发者

Finding the N th Occurrence of a Match line

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

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, fi开发者_如何学Gond 1 st occurrence of 'Ardei' and replace name with something else (perl).


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

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

and replace it with:

$1XYZ

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

A little demo:

#!/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;

will print:

Ardei
Mere
Pere
XYZ
Castraveti
Ardei


Ardei[\W\w]*?(Ardei)

will match exactly the second "Ardei" by its \1, so you can use it to replace exactly the second instance.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜