在Perl正则表达式"find & replace"中,如何单独挑选出每个匹配结果?

In Perl regex "find & replace", how to individually pick out each match result?

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

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 ) {
                push (@comments, );
                }
        }

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 提前~

您可以使用 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, );"foo"}eg;

print $_ foreach (@comments);

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

备注:

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