我有一个文本,我想在其中找到所有匹配项
(例如每个匹配的模式/d.g/
)
我需要在列表中并从原始文本中删除的那些模式。
操作上:dog and dig where dug in dug
应该给我:(狗,挖,挖,挖)。
文本应更改为:and where in
我可以通过两次传递文本来做到这一点,但这会是双重工作吗?
这是另一种选择:
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
尝试这样做:
$_ = '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'
语句是三元运算符我会这样写
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