Perl regex returns only one value in a list context, even if multiple matches are possible

I work with perl regex like this:

/(^.*)XXX/g 

I want this regular expression to match the text type

 ******XXX****XXX***XXX 

so in this case regexp will match 3 times and provide the following results:

 ******XXX****XXX*** ******XXX**** ****** 

However, when I put this regular expression in a list context like this

 while($_=~/(^.*)XXX/g) 

there is only one match, and that’s

 ******XXX****XXX*** 

Where am I mistaken?

+4
source share
4 answers

You need to change your loop:

 $_ = "******XXX****XXX***XXX"; while(/(.*)XXX/) { print $1,"\n"; $_=$1; } 

The corresponding result is found in $1 , and the variable you are matching is $_ .

+6
source

If you want to use $ $ PREMATCH`, this will give the desired result:

 my $inp = "******XXX****XXX***XXX"; while ($inp =~ /XXX/g) { print $`, "\n"; } 

output:

 ****** ******XXX**** ******XXX****XXX*** 

Your regular expression fails because ^.* Greedily matches "everyone."

+2
source

I would do it like this:

 $str = '******XXX****XXX***XXX'; sub backwards { if( $_[0] =~ /(.*)XXX.*?$/) { print $1, "\n"; backwards($1); } } backwards($str); 

output:

 ******XXX****XXX*** ******XXX**** ****** 
+1
source

Here's how to find all possible matches:

 local our @matches; /^(.*)XXX(?{ push @matches, $1 })(?!)/sg; say for @matches; # Or whatever 
+1
source

All Articles