perl:全局匹配,保存和替换正则表达式的最佳方式

Eri*_*ikR 5 regex perl

在字符串中,我想在字符串中查找正则表达式的所有匹配项,保存匹配项并替换匹配项.有没有一个光滑的方式来做到这一点?

例:

my $re = qr{\wat};
my $text = "a cat a hat the bat some fat for a rat";
... (substitute $re -> 'xxx' saving matches in @matches)
# $text -> 'a xxx a xxx the xxx some xxx for a xxx'
# @matches -> qw(cat hat bat fat rat)
Run Code Online (Sandbox Code Playgroud)

我试过了,@matches = ($text =~ s{($re)}{xxx}g)但它给了我一个数.

我是否必须在模式的末尾添加一些可执行代码$re

更新:这是一个使用代码执行扩展模式的方法(?{ ... }):

use re 'eval';  # perl complained otherwise
my $re = qr{\wat};
my $text = "a cat a hat the bat some fat for a rat";

my @x;
$text =~ s{ ($re)(?{ push(@x, $1)}) }{xxx}gx;

say "text = $text";
say Dumper(\@x); use Data::Dumper;
Run Code Online (Sandbox Code Playgroud)

FMc*_*FMc 3

这与您的更新中的方法类似,但更容易阅读:

$text =~ s/($re)/push @x, $1; 'xxx'/ge;
Run Code Online (Sandbox Code Playgroud)

或者这样(可能更慢):

push @x, $1 while $text =~ s/($re)/xxx/;
Run Code Online (Sandbox Code Playgroud)

但是,说实话,不光滑有什么问题吗?

my @x = $text =~ /($re)/g;
$text =~ s/($re)/xxx/g;
Run Code Online (Sandbox Code Playgroud)