in reply to Practical use cases for \K in regex

Good question. I think it is mostly historical these days. If you peruse the docs for 5.10 (when \K was introduced) they say this:

There is a special form of [positive look-behind], called \K, which causes the regex engine to "keep" everything it had matched prior to the \K and not include it in $&. This effectively provides variable length look-behind. The use of \K inside of another look-around assertion is allowed, but the behaviour is currently not well defined.

For various reasons \K may be significantly more efficient than the equivalent (?<=...) construct, and it is especially useful in situations where you want to efficiently remove something following something else in a string. For instance

s/(foo)bar/$1/g;

can be rewritten as the much more efficient

s/foo\Kbar//g;

So back then you could get variable-length look-behind using \K. Now it's only needed in the situation you describe where there might be a longer-than-the-limit variable look-behind, AIUI.


🦛