Perl正则表达式从替换中返回匹配项

4

我尝试同时删除和存储某个字符串中所有匹配的正则表达式。 要将字符串中的匹配返回到数组中,可以使用

my @matches = $string=~/$pattern/g;

我希望能够使用类似的模式来进行替换正则表达式。当然,其中一种选项是:

my @matches = $string=~/$pattern/g;
$string =~ s/$pattern//g;

但是是否真的没有办法在不让正则表达式引擎两次扫描完整个字符串的情况下完成这个操作呢?类似于

my @matches = $string=~s/$pattern//g

除此之外,这仅会返回订阅数,而不考虑列表上下文。作为安慰奖,我也会采用使用qr//的方法,在其中可以简单地修改引用的正则表达式为子正则表达式,但我不知道是否可能实现(这也不能排除两次搜索同一字符串的可能)。

请给出一个真实的例子,说明您要做什么。显示$string$pattern与编写eval $program相比,几乎没有什么用处。 - Borodin
2个回答

7
也许以下内容会有所帮助:
use warnings;
use strict;

my $string  = 'I thistle thing am thinking this Thistle a changed thirsty string.';
my $pattern = '\b[Tt]hi\S+\b';

my @matches;
$string =~ s/($pattern)/push @matches, $1; ''/ge;

print "New string: $string; Removed: @matches\n";

输出:

New string: I   am    a changed  string.; Removed: thistle thing thinking this Thistle thirsty

1
这里还有另一种方法来完成替换,而不需要在替换中执行Perl代码。诀窍在于s///g每次只返回一个捕获,并且如果没有匹配,则返回undef,从而退出while循环。
use strict;
use warnings;
use Data::Dump;

my $string = "The example Kenosis came up with was way better than mine.";
my @matches;

push @matches, $1 while $string =~ s/(\b\w{4}\b)\s//;

dd @matches, $string;

__END__

(
  "came",
  "with",
  "than",
  "The example Kenosis up was way better mine.",
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接