nandn has asked for the wisdom of the Perl Monks concerning the following question:

Hi, What's a nice piece of code to identify the last occurence of a pattern? Example: - String: ABCD EF GHI JKL MN OPQRST UV WXYZ - Pattern: two characters isolated by spaces - Returns: UV Any suggestions? Thanks.

Replies are listed 'Best First'.
Re: Get the last occurence of a pattern (2)
by tye (Sage) on Jun 14, 2007 at 05:36 UTC
    Update: Not:
    my $last= $string =~ /.*(PATTERN)/s;

    but

    my $last= ( $string =~ /(PATTERN)/g )[-1];

    or (first technique fixed in two different ways)

    my $last= $string =~ /.*(PATTERN)/s ? $1 : undef; # or my( $last )= $string =~ /.*(PATTERN)/sg;

    - tye        

Re: Get the last occurence of a pattern
by moritz (Cardinal) on Jun 14, 2007 at 11:08 UTC
    m/(PATTERN).*?$/

    Doesn't work, please ignore

      Not really:

      perl -le "$pat=qr/ \w\w /;$_='ABCD EF GHI JKL MN OPQRST UV';m/($pat).* +?$/ or die;print $1"

      prints EF, because the pattern matches at the earliest possible location. A possible fix would be to prepend a greedy .* which pushes the start of the following pattern as far to the right as possible:

      m/.*(PATTERN).*?$/

      The trailing .*?$ is superfluous, because the pattern will either match or not, regardless of the anchor.

        Note that my two solutions aren't identical. Given your pattern of / \w\w /, you'd want to use /.*($PATTERN)/ not ( /($PATTERN)/g )[-1] because the second case wouldn't DWIM with "overlapping matches":

        my $last= ( " AB CDE FG HI JKL " =~ /( \w\w )/g )[-1]; print $last, $/; __END__ prints " FG " (not " HI ")

        You could "fix" my second technique by switching the pattern to /(?<= )\w\w(?= )/ so that matches never overlap.

        But that doesn't make the second choice "better". There are also patterns where the second technique won't DWIM but the first technique will. In particular, patterns that need to be greedy need the first technique or else they won't be greedy:

        my( $last )= " AB CDE FG HI JKL " =~ /.*(\w+)/sg; print $last, $/; __END__ prints "L" (not "JKL")

        Which begs one to ask what technique will get the "last match" and DWIM in the face of a greedy pattern with overlapping matches.

        my $string= " AB CDE FG HI JKL "; my $PATTERN= qr/(?! F)(?: \w+){1,3} /; # (match space-separated words where the first doesn't start with "F") my( $last )= $string =~ /.*($PATTERN)/sg; print $last, $/; $last= ( $string =~ /($PATTERN)/g )[-1]; print $last, $/; __END__ prints: JKL JKL never: HI JKL

        This illustrates an important point about regular expressions. They prefer to be greedy but more than that they prefer to match left-most (that is, to match earlier in the string rather than further to the right in the string). That is why texts on regexes say "greedy" as "left-most longest" (and not "longest left-most").

        So I've hypothesized a case where we first want the match to end as far right as possible and second want the match to start as far left as possible. One way to get this from the regex engine is to use a "sexeger" (reverse the string and compose the regex backward), a technique coined by japhy:

        my $string= reverse " AB CDE FG HI JKL "; my $PATTERN= qr/(?: \w+){1,3}(?<!F) /; # (match space-separated words where the last doesn't end with "F") my $last= $string =~ /($PATTERN)/ ? $1 : undef; print reverse($last) . $/; __END__ prints " HI JKL " !

        You could also get it with more "brute force":

        my $string= " AB CDE FG HI JKL "; my $PATTERN= qr/(?! F)(?: \w+){1,3} /; # (match space-separated words where the first doesn't start with "F") my $last; my $end= -1; while( $string =~ /(?=($PATTERN))/g ) { my $stop= $+[-1]; if( $end < $stop ) { $last= $1; $end= $stop; } } print $last, $/; __END__ prints " HI JKL " !

        - tye