如何捕获全局正则表达式替换中的每个匹配?

问题描述 投票:1回答:4

我意识到可以通过一些变通方法来实现,但是我希望有一种更简单的方法(因为我经常使用这种类型的表达式)。

给出示例字符串:

my $str = "An example: sentence!*"

正则表达式可用于匹配每个标点符号并将它们捕获在数组中。此后,我可以简单地重复正则表达式并替换匹配项,如以下代码所示:

push (@matches, $1), while ($str =~ /([\*\!:;])/);
$str =~ s/([\*\!:;])//g;

是否有可能在Perl中将其组合成一个步骤,在其中进行替换是令人作呕的,同时还要在替换的匹配项上保持制表符?

regex perl substitution
4个回答
3
投票

用途:

my $str = "An example: sentence!*";
my @matches = $str =~  /([\*\!:;])/g;
say Dumper \@matches;
$str =~ tr/*!:;//d;

输出:

$VAR1 = [
          ':',
          '!',
          '*'
        ];

2
投票

是,有可能。

my @matches;
$str =~ s/[*!:;]/ push @matches, $&; "" /eg;

但是,我不相信以上内容比以下内容更快或更清晰:

my @matches = $str =~ /[*!:;]/g;
$str =~ tr/*!:;//d;

0
投票

尝试:

my $str = "An example: sentence!*";

push(@mys, ($str=~m/([^\w\s])/g));

print join "\n", @mys;

谢谢。


0
投票

您可以嵌入代码以在正则表达式中运行:

my @matches;
my $str = 'An example: sentence!*';
$str =~ s/([\*\!:;])(?{push @matches, $1})//g;

但是通过简单的匹配,我将分别进行捕获和替换。

© www.soinside.com 2019 - 2024. All rights reserved.