Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to limit the found matches on perl using regex?

Tags:

regex

perl

I come to ask for your aid after a lot of research on this matter:

I'm trying to limit the repetition of the substitutions that a Perl regex does on a big text. I've searched in Google and found that the format is {2,3} (min, max) however this seems to be for a different way that the syntax I'm using.

$replaced=~s/$var/$var2/g; # replaces all ocurrences
$replaced=~s/$var/$var2/;  # replaces only first one

my non optimal solution:

for($i=0; $i<8; $i++){

    $replaced=~s/$var/$var2/;
}

What I have tried:

$replaced=~s/$var/$var2/{8};
$replaced=~s/$var/$var2{8}/;

Any help will be appreciated!

edit: OK so pretty much there has to be a loop involved huh.. isn't that weird that there is not a built in parameter to limit it??

like image 449
isJustMe Avatar asked Nov 11 '11 17:11

isJustMe


1 Answers

The answers with \G are probably the most practical way to do what you want, but just for fun or edification or whatever, here is another way (requiring perl 5.10 or higher), using code assertions and the backtracking control verbs (*COMMIT) and (*FAIL):

my $str = "Bananas in pajamas are coming down the stairs";
my $limit = 3;
my $count;

$str =~ s/(*COMMIT)(?(?{ $count++ >= 3 })(*FAIL))a/A/g;
say $str;

which leaves the text "BAnAnAs in Pajamas are coming down the stairs" in $str — only the first three "a"s were affected and it stops scanning the string for more matches after the third.

like image 62
hobbs Avatar answered Sep 19 '22 20:09

hobbs