Perl: The Best Way to Match, Save, and Replace Regular Expressions Worldwide

In the string, I want to find all the regular expression matches in the string, save the matches, and replace the matches. Is there any way to do this?

Example:

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)

I tried: @matches = ($text =~ s{($re)}{xxx}g)but he gives me the bill.

Should I add executable code at the end of the template $re?

Update: Here is a method that uses an extended code execution pattern (?{ ... }):

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;
+5
source share
3 answers

This is similar to the approach in your update, but a little easier to read:

$text =~ s/($re)/push @x, $1; 'xxx'/ge;

Or this way (maybe slower):

push @x, $1 while $text =~ s/($re)/xxx/;

But, is there really something wrong with unslick?

my @x = $text =~ /($re)/g;
$text =~ s/($re)/xxx/g;
+3
source

"slick" " " " ", , , :

my ($temp, @matches);

push @matches, \substr($text, $-[0], $+[0] - $-[0]) while $text =~ /\wat/g;

$temp = $$_, $$_ = 'xxx', $_ = $temp for reverse @matches;
+3
my @x = map { $str =~ s/$_/xxx/; $_ } $str =~ /($re)/g;
+1
source

All Articles