2

我有一个文本,我想在其中找到所有匹配项
(例如每个匹配的模式/d.g/

我需要在列表中并从原始文本中删除的那些模式。

操作上:dog and dig where dug in dug应该给我:(狗,挖,挖,挖)。

文本应更改为:and where in

我可以通过两次传递文本来做到这一点,但这会是双重工作吗?

4

3 回答 3

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
于 2012-12-20T21:41:50.027 回答
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'语句是三元运算符
于 2012-12-20T21:26:25.680 回答
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 
于 2012-12-21T01:42:05.563 回答