Regular Expressions Simulating variable-length lookbehind with \K


Example

Some regex flavors (Perl, PCRE, Oniguruma, Boost) only support fixed-length lookbehinds, but offer the \K feature, which can be used to simulate variable-length lookbehind at the start of a pattern. Upon encountering a \K, the matched text up to this point is discarded, and only the text matching the part of the pattern following \K is kept in the final result.

ab+\Kc

Is equivalent to:

(?<=ab+)c

In general, a pattern of the form:

(subpattern A)\K(subpattern B)

Ends up being similar to:

(?<=subpattern A)(subpattern B)

Except when the B subpattern can match the same text as the A subpattern - you could end up with subtly different results, because the A subpattern still consumes the text, unlike a true lookbehind.