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 " !
|