【发布时间】:2010-03-31 18:54:12
【问题描述】:
在extracting the n'th regex match 上的一个问题之后,我现在需要替换匹配项(如果找到)。
我认为我可以定义提取子例程并使用/e 修饰符在替换中调用它。我显然错了(诚然,我有一个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'
当然,这种技术还有许多其他问题:
- 如果不同位置有相同的匹配怎么办?
- 如果找不到匹配项怎么办?
鉴于这种情况,我想知道这可以通过什么方式实现。
【问题讨论】:
-
你不能匹配表达式
n-1次,然后在第 n 次匹配时进行替换吗? -
@mmyers:您可能在这里有所了解,但是即使我将替换部分作为子例程的一部分,仍然存在要应对不同索引处的别名匹配问题。
-
如果有多个匹配项,要全部替换吗?
-
@leonbloy:不,只有索引指定的那个。
标签: regex perl substitution