Regex global matching?
I was wondering if there is a global matching flag, considering there is a global replacement flag (/g)
I'm using this workaround to make multiple matches in a string
while(!$stop_var)
{
if($source =~ /(PATTERN)/i)
{
push(@matches, $1);
$source = $';
}
else
{
$stop_var =1;
}
}
is there an easier way?
terabyte
Junior Poster in Training
68 posts since Oct 2010
Reputation Points: 10
Solved Threads: 4
push @matches, $1 while ($source=~ m{(PATTERN)}g);
Is this you want ?
k_manimuthu
Junior Poster in Training
93 posts since Jun 2009
Reputation Points: 55
Solved Threads: 24
Thanks k_manimuthu worked perfectly!
terabyte
Junior Poster in Training
68 posts since Oct 2010
Reputation Points: 10
Solved Threads: 4
push @matches, $1 while ($source=~ m{(PATTERN)}g);
Is this you want ?
That looks good. Alternatively, you can assign the result of a global match to an array directly, without a loop.
#!/usr/bin/perl
use strict;
use warnings;
my $source = '1 door and only 1 and yet its sides are 2';
my $pattern = qr/\ba\w*\b/;
my @matches = $source =~ m/$pattern/g;
print "Matches are:\n", join "\n", @matches;
#Matches are:
#and
#and
#are
d5e5
Practically a Posting Shark
810 posts since Sep 2009
Reputation Points: 159
Solved Threads: 159