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??
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With