Regular Expressions Search and replace using \K operator


Example

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