Members Only

GREP of the Month: Keep Out

Try this obscure but powerful alternative when a traditional GREP lookbehind expression won’t do the trick.

This article appeared in Issue 73 of InDesign Magazine.

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!

Bookmark
Please login to bookmark Close

Not a member yet?

Get unlimited access to articles and member-only resources with a CreativePro membership.

Become a Member

Comments (1)

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. Steve Laskevitch

    There is a new post-it on my screen’s bezel–thank you!