在字符串中,我想在字符串中查找正则表达式的所有匹配项,保存匹配项并替换匹配项.有没有一个光滑的方式来做到这一点?
例:
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)但它给了我一个计数.
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;