in reply to Re^4: Does Perl support a given number of replacements ?
in thread Does Perl support a given number of replacements ?
Another way would be to combine a regular expression look-ahead with pos to find all of the potential positions in the text where a substitution might be made and then use substr to make the substitutions, working from the last substitution forwards to avoid the positions going out of kilter.
use strict; use warnings; my $text = q{abaacaa}; my $repCt = 3; my $replace = q{a}; my $len = length $replace; my $with = q{aa}; print qq{$text\n}; my @posns; push @posns, pos $text while $text =~ m{(?=$replace)}g; print qq{@posns\n}; substr $text, $_, $len, $with for reverse @posns[ 0 .. $repCt - 1 ]; print qq{$text\n};
The output.
abaacaa 0 2 3 5 6 aabaaaacaa
I hope this is of interest.
Cheers,
JohnGG
|
|---|