Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl regular expression returns only one value in list context even if multiple matching is possible

Tags:

regex

perl

I am working with a Perl regular expression of this kind:

/(^.*)XXX/g

I want this regexp to match text of the type

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

so that in this case the regexp would match three times and provide these results:

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

However, when I put this regexp in a list context like this

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

there's only one match and it is

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

Where am I going wrong?

like image 952
Tito Candelli Avatar asked Jan 14 '23 08:01

Tito Candelli


2 Answers

You need to change your loop:

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

The matched result is found in $1 while the variable you're matching to is $_.

like image 178
Patrick B. Avatar answered Jan 31 '23 07:01

Patrick B.


If you are willing to use $` ($PREMATCH), this will get your desired result:

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

output:

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

Your regex fails, because ^.* matches 'everything' greedily.

like image 35
Ekkehard.Horner Avatar answered Jan 31 '23 09:01

Ekkehard.Horner