Regular Expressions Lookahead and Lookbehind Simulating variable-length lookbehind with \K

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any Regular Expressions Question?