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?
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 $_
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With