How can I substitute the nth occurrence of a match in a Perl regex?
Posted
by Zaid
on Stack Overflow
See other posts from Stack Overflow
or by Zaid
Published on 2010-03-31T18:54:12Z
Indexed on
2010/03/31
19:03 UTC
Read the original article
Hit count: 391
Following up from an earlier question on extracting the n'th regex match, I now need to substitute the match, if found.
I thought that I could define the extraction subroutine and call it in the substitution with the /e
modifier. I was obviously wrong (admittedly, I had an XY problem).
use strict;
use warnings;
sub extract_quoted { # à la codaddict
my ($string, $index) = @_;
while($string =~ /'(.*?)'/g) {
$index--;
return $1 if(! $index);
}
return;
}
my $string = "'How can I','use' 'PERL','to process this' 'line'";
extract_quoted ( $string, 3 );
$string =~ s/&extract_quoted($string,2)/'Perl'/e;
print $string; # Prints 'How can I','use' 'PERL','to process this' 'line'
There are, of course, many other issues with this technique:
- What if there are identical matches at different positions?
- What if the match isn't found?
In light of this situation, I'm wondering in what ways this could be implemented.
© Stack Overflow or respective owner