[San-Diego-pm] Regular Expressions: zero-width negative look-behind assertion

Bill Davidson billdav at cox.net
Sun Jan 30 23:10:27 PST 2005


I'd like to use a zero-width negative look-behind assertion for something
I'm working on.  Unfortunately, for some reason, the implementers of
Perl's RE engine decided that it should only be able to do a fixed width
look-behind.

I'd like to do this:

	if ( $myvar =~ /(?<!foo\d+)bar$/ ){

Unfortunately, Perl barfs on that because of the "+".

Error message:
	Variable length lookbehind not implemented in regex;

BTW, I'm using Perl 5.8.4 and this behaviour appears to be consistent
with the perlre documentation.  Requiring an RE to be fixed width is
very limiting.  I don't like it.

It works perfectly without the "+":

	if ( $myvar =~ /(?<!foo\d)bar$/ ){

if $myvar has exactly one digit between foo and bar.  Unfortunately, I
won't know how many digits are there normally.  If foo is there then there
will always be at least one digit.  If foo is not there, then digits may
or may not be there and I'd want a positive match in either case.

The only way I've figured out to get around this is:

	if ( $myvar =~ /bar$/ && $myvar !~ /foo\d+bar$/ ){

I'd really prefer to do it in only one match operation.  Does anybody
on san-diego-pm know a way?

--Bill Davidson


More information about the San-Diego-pm mailing list