However, any alternative that starts earlier in the target string will be matched, regardless of a longer string later. Given multiple alternatives, you'll have to find all of the matches, and then pick the longest one.
There are a couple of ways to do this. One is to get all matches for each alternative, then sort the results by length. Something like this (untested):
my $string = "an apple in the fridge"; my @regexes = ("an apple", "apple in a fridge", qr/(?:pine)?apples/); my %matches; for my $regex (@regexes) { my @matches = $string =~ /$regex/; for my $match (@matches) { $matches{$match} = 1; # or increment to keep score } } my @matches_sorted_by_length = sort {length($a) <=> length($b)} keys % +matches; print "Longest match is $matches_sorted_by_length[-1]\n";
However, this ignores the edge case where the same substring overlaps itself, like "hearth" in "hearthearth". If the regexes are not fixed length and/or have optional parts, some matches might be missed (including the longest one).
The improvement to the above is to walk through the target string using pos to start matching just after the last match started. There are several examples you can find, which I'm too short of time to look up at the moment.
-QM
--
Quantum Mechanics: The dreams stuff is made of
In reply to Re: Regex Match : Doesn't return the longest match when there's a common word present in the group
by QM
in thread Regex Match : Doesn't return the longest match when there's a common word present in the group
by ssc37
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |