954,523 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

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
 
use strict;
use warnings;

my $pattern="1234";

undef($/);
my @array;
my $count;
while(<DATA>){
	$count=(@array)=$_=~/$pattern.{1}/gi;
}

print "$count\n";
print "@array\n";


__DATA__
12348097790797401234790
87989871234908098098909
87987983412344908098098
mitchems
Posting Whiz in Training
295 posts since Feb 2009
Reputation Points: 26
Solved Threads: 38
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You