Regular Expressions

Match Reset: \K

Remarks#

Regex101 defines \K functionality as:

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

The \K escape sequence is supported by several engines, languages or tools, such as:

  • boost (since ???)
  • grep -P                                                     ← uses PCRE
  • Oniguruma (since 5.13.3)
  • PCRE (since 7.2)
  • Perl (since 5.10.0)
  • PHP (since 5.2.4)
  • Ruby (since 2.0.0)

…and (so far) not supported by:

  • .NET
  • awk
  • bash
  • GNU
  • ICU
  • Java
  • Javascript
  • Notepad++
  • Objective-C
  • POSIX
  • Python
  • Qt/QRegExp
  • sed
  • Tcl
  • vim
  • XML
  • XPath

Search and replace using \K operator

Given the text:

foo: bar

I would like to replace anything following “foo: ” with “baz”, but I want to keep “foo: “. This could be done with a capturing group like this:

s/(foo: ).*/$1baz/

Which results in the text:

foo: baz

Example 1

or we could use \K, which “forgets” all that it has previously matched, with a pattern like this:

s/foo: \K.*/baz/

The regex matches “foo: ” and then encounters the \K, the previously match characters are taken for granted and left by the regex meaning that only the string matched by .* will be replaced by “baz”, resulting in the text:

foo: baz

Example 2


This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow