What Does "\K" Mean in Regex?

marounmaroun

Maroun Maroun

Posted on April 20, 2020

What Does "\K" Mean in Regex?

Since not all regex flavors support lookarounds, Perl introduced the match reset - \K (bolded is mine):

\K resets the starting point of the reported match. Any previously consumed characters are no longer included in the final match

To make the explanation short, consider the following simple Regex:

a\Kb

When "b" is matched, \K tells the Regex engine to pretend that the match attempt started at this position.

~$ echo 'hello world' | grep -oP 'hello \K(world)'
world
~$ echo 'hello world' | grep -oP 'hello (world)'
hello world
💖 💪 🙅 🚩
marounmaroun
Maroun Maroun

Posted on April 20, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related