#! /usr/local/bin/perl -w #LongestMatch.pl #from Friedl: Mastering Regular Expressions, pp. 334-335 use strict; my $longest_match = undef; # We'll keep track of the longest match here my $RecordPossibleMatch = qr{ (?{ # Check to see if the current match ($&) is the longest so far if (not defined($longest_match) or length($&) > length($longest_match)) { $longest_match = $&; } }) (?!) # Force failure so we'll backtrack to find further "matches" }x; while (<>) { chomp; $_ =~ m{ [abcdef]{0,1} [gh]{0,1} [ij]{0,1} [klmn]{0,1} [op]{0,1} [qr]{0,1} [astuv]{0,1} [gh]{0,1} [wxyz]{0,1} $RecordPossibleMatch }x; # Now report the accumulated result, if any if (defined($longest_match)) { print "$longest_match\n"; } else { print ".\n"; } $longest_match = undef; }