Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Practical use cases for \K in regex

by ikegami (Patriarch)
on Oct 05, 2023 at 20:07 UTC ( [id://11154833] : note . print w/replies, xml ) Need Help??


in reply to Practical use cases for \K in regex

It simplifies.

say "foo: bar" =~ s/^ ( \w+: \s* ) bar /${1}baz/xr;
vs
say "foo: bar" =~ s/^ \w+: \s* \K bar /baz/r;

It helps avoid avoid repetition.

say "a:b:c:d" =~ s/ :\K [^:]+ (?=:) / uc($&) /xegr;
vs
say "a:b:c:d" =~ s/ : [^:]+ (?=:) / ":" . uc($&) /xegr;

It effectively permits variable-length lookbehinds or makes them faster.

say "foo: bar" =~ s/ (?<= ^ \w+: \s* ) bar /baz/xr;
vs
say "foo: bar" =~ s/^ \w+: \s* \K bar /baz/r;

The former was an error when \K was introduced. Even now, it's experimental, and there's a maximum to how much it will look behind this way.