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 appears in Issue 73 of InDesign Magazine.
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!
Recommended for you
Cleaning Up White Space Problems in Word Files
Proven methods for removing messy white space characters that can cause trouble...
Making Catalogs that Work (with Less Work)
Transform your catalog designs from ho-hum to high performing with these tips.
Designing Book Covers in InDesign
Learn how the key to designing a book jacket lies in the execution of the InDesi...
