imitatio creatio co we łbie piszczy

11Jun/08Off

variable length positive lookbehind in perl regex

perlre says it does not support lookbehind matches with arbitrary length.

here is a workaround


#!perl -l -w
use strict;
#
print my $txt = 'Alice has a fish. It is a nice fish.
Bob has a dog. John has a cat.
Line 3 is not important.
Filip has a perl.
---------------------------';
#
=pod WE WANT THIS but this gives Perl error.
while ( $txt =~ m{(?<=$behind_re)($match_re)(?=$ahead_re)}g ) {
print $&;
}
=cut
#
my $behind_re = qr/[A-Z][a-z]+ has a /; # Filip has a
my $match_re = qr/\w+/i; # perl
my $ahead_re = qr/\./; # .
#
while ( $txt =~ m{($behind_re)}g ) { # we look for behind match globally,
if ( $txt =~ m{\G($match_re)(?=$ahead_re)} ) { # we search for the rest anchored at each found position
print $&; # voila
}
}
#

Comments (0) Trackbacks (0)

Sorry, the comment form is closed at this time.

Trackbacks are disabled.