Perl正则表达式从替换返回匹配
发布时间:2020-12-16 06:19:10 所属栏目:大数据 来源:网络整理
导读:我试图同时删除并存储(到一个数组)字符串中的一些正则表达式的所有匹配. 要将字符串中的匹配项返回到数组中,您可以使用 my @matches = $string=~/$pattern/g; 我想对替换正则表达式使用类似的模式.当然,一个选择是: my @matches = $string=~/$pattern/g;$st
我试图同时删除并存储(到一个数组)字符串中的一些正则表达式的所有匹配.
要将字符串中的匹配项返回到数组中,您可以使用 my @matches = $string=~/$pattern/g; 我想对替换正则表达式使用类似的模式.当然,一个选择是: my @matches = $string=~/$pattern/g; $string =~ s/$pattern//g; 但是如果没有在整个字符串上运行两次正则表达式引擎,真的没有办法做到这一点吗?就像是 my @matches = $string=~s/$pattern//g 除了这将只返回子数,不管列表上下文.作为一个安慰奖,我还会采用一种方法来使用qr //我可以简单地将引用的正则表达式修改为子正则表达式,但我不知道这是否可能(并且这不会妨碍搜索相同的字符串两次). 解决方法
也许以下内容会有所帮助:
use warnings; use strict; my $string = 'I thistle thing am thinking this Thistle a changed thirsty string.'; my $pattern = 'b[Tt]hiS+b'; my @matches; $string =~ s/($pattern)/push @matches,$1; ''/ge; print "New string: $string; Removed: @matchesn"; 输出: New string: I am a changed string.; Removed: thistle thing thinking this Thistle thirsty (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |