in reply to Regex Match : Doesn't return the longest match when there's a common word present in the group

Perl tries to match the longest possible, but it tries to match as soon as possible first. "an apple" begins before "apple in the fridge", that's why it wins in this case.

You can use the look-ahead assertion to search for overlapping strings in a loop:

#! /usr/bin/perl use strict; use warnings; my $string = "an apple in the fridge"; my $match = q(); length $1 > length $match and $match = $1 while $string =~ /(?=(apple in the fridge|an apple))/g; print "$match\n";
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
  • Comment on Re: Regex Match : Doesn't return the longest match when there's a common word present in the group
  • Download Code

Replies are listed 'Best First'.
Re^2: Regex Match : Doesn't return the longest match when there's a common word present in the group
by ssc37 (Acolyte) on Feb 01, 2015 at 18:47 UTC
    That's exactly what i was looking for :) Thanks you