例:
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 otherwisemy $re = qr{\wat};my $text = "a cat a hat the bat some fat for a rat";my @x;$text =~ s{ ($re)(?{ push(@x,)}) }{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:全局匹配,保存和替换正则表达式的最佳方式全部内容,希望文章能够帮你解决perl:全局匹配,保存和替换正则表达式的最佳方式所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)