GREP of the Month: Keep Out
Try this obscure but powerful alternative when a traditional GREP lookbehind expression won’t do the trick.


When a traditional lookbehind expression won’t do the trick, try this obscure but powerful alternative. In Issue 63 of InDesign Magazine, David Blatner discussed InDesign’s positive lookbehind feature. He ended his piece with the words “the code after the =
symbol must specify an exact number of characters. That is, you might expect the expression (?<=s+)u
would mean ‘an uppercase letter after a string of one or more spaces.’ Unfortunately, the +
(‘one or more’) part makes it fail because it’s too open-ended.” The only way in which you could do variable-length expressions in a lookbehind was to list each variation in a separate lookbehind and group them as alternatives. Thus, to find numbers preceded by the word Map, Figure, or Table, you had to resort to an unwieldy expression such as ((?<=Map )|(?<=Figure )|(?<=Table ))d+
. But this worked only if you knew the range of variation, so, yes, David was right, you can’t use the .
(dot) and +
operators in lookbehinds. That, until very recently, was what we all thought. But in CS6, Adobe introduced an operator that does allow lookbehinds that match variable-length text, namely K
(a classic Adobe Special: introduce something quite useful but don’t tell anybody about it). Using this class, David’s expression (?<=s+)u
can be rendered as s+Ku
. And the example I gave can be recast as (Map|Figure|Table)sKd+
. What K
actually means is “Keep the text matched so far out of the overall match.” This sounds strange, but to understand it, we can use a simple example, aKb
. This matches the b in ab. To do so, first it searches for a. When a is matched, K
says “remove a from
the overall match.” The search resumes, looking for (and matching) b. You can use K
just about anywhere. The main limitation is that it doesn’t work with negatives, so you can’t use it to find something that is not preceded by something else. But on the other hand, K
GREPs execute (marginally) quicker than classic lookbehinds. Try it!
Commenting is easier and faster when you're logged in!
Leave a Reply
Recommended for you

Illustrator Downloadable: Tropical Shadow Overlay Kit
Downloadables are an exclusive benefit for CreativePro members! (Not a member ye...

Illustrator Downloadable: Summer Citrus Pattern Set
Downloadables are an exclusive benefit for CreativePro members! (Not a member ye...

InDesign Downloadable: Tables SuperGuide
Downloadables are an exclusive benefit for CreativePro members! (Not a member ye...
There is a new post-it on my screen’s bezel–thank you!