加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 06:27:29 所属栏目:大数据 来源:网络整理
导读:在字符串中,我想在字符串中查找正则表达式的所有匹配项,保存匹配项并替换匹配项.有没有一个光滑的方式来做到这一点? 例: my $re = qr{wat};my $text = "a cat a hat the bat some fat for a rat";... (substitute $re - 'xxx' saving matches in @matches
在字符串中,我想在字符串中查找正则表达式的所有匹配项,保存匹配项并替换匹配项.有没有一个光滑的方式来做到这一点?

例:

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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读