Reply To: GREP Tricks: More LookBehind and LookAhead examples …

Home Page / Forums / General InDesign Topics (CLOSED) / GREP Tricks: More LookBehind and LookAhead examples … / Reply To: GREP Tricks: More LookBehind and LookAhead examples …

#72148
Allan Shearer
Participant

Cool! Thanks. Had never heard of \K. Thanks!

It’s not something that is available in the UI … guess you just gotta know about it.

Here’s what I’ve found on it, as posted in an Adobe forum:

————————snip————————
(?<=pattern) \K

A zero-width positive look-behind assertion. For example, /(?<=)\w+/ matches a word that follows a tab, without including the tab in $& . Works only for fixed-width look-behind.

There is a special form of this construct, 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;
————————snip————————

Allan

This article was last modified on December 9, 2014

Comments (0)

Loading comments...