继之前关于提取第 n 个正则表达式匹配的问题之后,我现在需要替换匹配项(如果找到)。
我认为我可以定义提取子例程并使用/e
修饰符在替换中调用它。我显然错了(诚然,我遇到了XY 问题)。
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'
当然,这种技术还有许多其他问题:
- 如果在不同的位置有相同的匹配怎么办?
- 如果找不到匹配项怎么办?
鉴于这种情况,我想知道这可以通过什么方式实现。