简体   繁体   English

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

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

In a string I want to find all matches of a regex in a string, save the matches and replace the matches.在一个字符串中,我想查找字符串中正则表达式的所有匹配项,保存匹配项并替换匹配项。 Is there a slick way to do that?有没有一种巧妙的方法来做到这一点?

Example:例子:

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)

I've tried: @matches = ($text =~ s{($re)}{xxx}g) but it gives me a count.我试过: @matches = ($text =~ s{($re)}{xxx}g)但它给了我一个计数。

Do I have to add some executable code onto the end of pattern $re ?我是否必须在模式$re的末尾添加一些可执行代码?

Update: Here is a method which uses the code execution extended pattern (?{... }) :更新:这是一个使用代码执行扩展模式(?{... })的方法:

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;

This is similar to the approach in your Update, but a bit easier to read:这类似于您的更新中的方法,但更容易阅读:

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

Or this way (probably slower):或者这样(可能更慢):

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

But, really, is there anything wrong with unslick ?但是,真的, unslick有什么问题吗?

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

If by "slick" you mean "employs uncommonly-used language features" or "will make other programmers scratch their heads," then maybe this is the solution for you:如果你所说的“光滑”是指“使用不常用的语言特性”或“会让其他程序员摸不着头脑”,那么也许这就是你的解决方案:

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