我有一个文字,我希望找到所有匹配项目
(例如,与/d.g/
匹配的每个模式)
我在列表中需要的那些模式,并从原始文本中删除。
操作:dog and dig where dug in dug
应该给我:
(狗,挖,挖,挖)。
文字应更改为:and where in
我可以通过两次传递文本来做到这一点,但这会是双重工作吗?
答案 0 :(得分:3)
这是另一种选择:
use strict;
use warnings;
my $str = 'dog and dig where dug in dug';
my @matches;
$str =~ s/\b(d.g)\b/push @matches, $1; ''/ge;
print $str, "\n";
print join ', ', @matches;
输出:
and where in
dog, dig, dug, dug
答案 1 :(得分:0)
尝试这样做:
$_ = 'dog and dig where dug in dug';
(/\b(d.g)\b/) ? push @_, $1 : print "$_ " for split /\s+/;
print "\n\narr:\n", join "\n", @_;
\b
是字边界(condition) ? 'if true' : 'if false'
语句是三元运算符答案 2 :(得分:0)
我会像这样写
use strict;
use warnings;
my $str = 'dog and dig where dug in dug';
my @matches;
push @matches, substr $str, $-[0], $+[0] - $-[0], '' while $str =~ /d.g/g;
print join(', ', @matches), "\n";
print $str, "\n";
<强>输出强>
dog, dig, dug, dug
and where in