Variable-length lookbehind-assertion alternatives for regular expressions Variable-length lookbehind-assertion alternatives for regular expressions python python

Variable-length lookbehind-assertion alternatives for regular expressions


Most of the time, you can avoid variable length lookbehinds by using \K.

s/(?<=foo.*)bar/moo/s;

would be

s/foo.*\Kbar/moo/s;

Anything up to the last \K encountered is not considered part of the match (e.g. for the purposes of replacement, $&, etc)

Negative lookbehinds are a little trickier.

s/(?<!foo.*)bar/moo/s;

would be

s/^(?:(?!foo).)*\Kbar/moo/s;

because (?:(?!STRING).)* is to STRING as [^CHAR]* is to CHAR.


If you're just matching, you might not even need the \K.

/foo.*bar/s/^(?:(?!foo).)*bar/s


For Python there's a regex implementation which supports variable-length lookbehinds:

http://pypi.python.org/pypi/regex

It's designed to be backwards-compatible with the standard re module.


You can reverse the string AND the pattern and use variable length lookahead

(rab(?!\w*oof)\w*)

matches in bold:

raboof rab7790oof raboo rabof rab rabo raboooof rabo

Original solution as far as I know by:

Jeff 'japhy' Pinyan