繁体   English   中英

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

[英]perl: best way to match, save and replace a regex globally

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

例子:

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)

我试过: @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;

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

$text =~ s/($re)/push @x, $1; 'xxx'/ge;

或者这样(可能更慢):

push @x, $1 while $text =~ s/($re)/xxx/;

但是,真的, unslick有什么问题吗?

my @x = $text =~ /($re)/g;
$text =~ s/($re)/xxx/g;

如果你所说的“光滑”是指“使用不常用的语言特性”或“会让其他程序员摸不着头脑”,那么也许这就是你的解决方案:

my ($temp, @matches);

push @matches, \substr($text, $-[0], $+[0] - $-[0]) while $text =~ /\wat/g;

$temp = $$_, $$_ = 'xxx', $_ = $temp for reverse @matches;
my @x = map { $str =~ s/$_/xxx/; $_ } $str =~ /($re)/g;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM