我试图同时删除并存储(到一个数组)字符串中的一些正则表达式的所有匹配.要将字符串中的匹配项返回到数组中,您可以使用
my @matches = $string=~/$pattern/g;
我想对替换正则表达式使用类似的模式.当然,一个选择是:
my @matches = $string=~/$pattern/g; $string =~ s/$pattern//g;
但是如果没有在整个字符串上运行两次正则表达式引擎,真的没有办法做到这一点吗?就像是
my @matches = $string=~s/$pattern//g
除了这将只返回子数,不管列表上下文.作为一个安慰奖,我还会采用一种方法来使用qr //我可以简单地将引用的正则表达式修改为子正则表达式,但我不知道这是否可能(并且这不会妨碍搜索相同的字符串两次).
也许以下内容会有所帮助:
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