在Perl regex" find&替换",如何单独挑选每个匹配结果?

时间:2016-02-02 04:49:47

标签: regex perl replace find match

我想使用Perl执行"搜索和替换"在文本文件上,并在替换完成时将每个匹配结果(作为元素)存储到数组中。我试过这个:

my $txt = "
this is a statement //this is comment
//this is a line of comment
more statements //more comments
";

## foreach or while
while ($txt =~ s/(\/\/.*?\n)/foo/gs) {
        if(defined $1) {
                push (@comments, $1);
                }
        }

foreach (0..$#comments) {
        print "\@comments[$_]= @comments[$_]";
        }

====>然而,结果只给了我:

@comments[0]= //more comments

然而,我期望的是:

@comments[0]= //this is comment
@comments[1]= //this is a line of comment
@comments[2]= //more comments

有关此问题的任何提示?谢谢& 3q提前〜

1 个答案:

答案 0 :(得分:2)

您可以使用e修饰符(see perlretut)执行替换内的代码:

my $txt = "
this is a statement //this is comment
//this is a line of comment
more statements //more comments
";

my @comments;

$txt =~ s{(//.*\n)} {push(@comments, $1);"foo"}eg;

print $_ foreach (@comments);

其他方式:由于您正在寻找内联注释,您还可以使用循环并且不使用g修饰符逐行工作。

注意:

  • 如果您想保留换行符,请从模式中删除\n
  • 从代码中删除注释可能比您想象的更复杂。例如,字符序列//可以包含在字符串中,因此更安全的方法是使用适当的解析器。
相关问题