[英]perl: best way to match, save and replace a regex globally
在一個字符串中,我想查找字符串中正則表達式的所有匹配項,保存匹配項並替換匹配項。 有沒有一種巧妙的方法來做到這一點?
例子:
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;
這類似於您的更新中的方法,但更容易閱讀:
$text =~ s/($re)/push @x, $1; 'xxx'/ge;
或者這樣(可能更慢):
push @x, $1 while $text =~ s/($re)/xxx/;
但是,真的, unslick有什么問題嗎?
my @x = $text =~ /($re)/g;
$text =~ s/($re)/xxx/g;
如果你所說的“光滑”是指“使用不常用的語言特性”或“會讓其他程序員摸不着頭腦”,那么也許這就是你的解決方案:
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.