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

前端之家收集整理的这篇文章主要介绍了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)

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

解决方法

如果用“光滑”来表示“使用不常用的语言功能”或“会让其他程序员划伤”,那么也许这就是你的解决方案:

my ($temp,@matches);

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

$temp = $$_,$$_ = 'xxx',$_ = $temp for reverse @matches;

猜你在找的Perl相关文章