First, order the alternatives by priority. If this is purely by length, put the longest one first.

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.