GREP of the Month: Lookahead
Peter Kahrel shows how to use Lookahead in an InDesign GREP search to target a text string by what follows it.
This article appears in Issue 86 of InDesign Magazine.
Many find-and-replace actions involve finding a string and replacing—or applying some formatting to—only part of the found string. But if you find a string and want to apply formatting to just part of it, you have to select the part of the string you’re interested in, do the replacement or formatting, and then find the next occurrence. All this can become very tedious very quickly. Fortunately, GREP offers a way to do conditional finds, such as “find the word Figure only if it’s followed by a digit.” These conditionals are called “lookahead,” and their general format is (?=). In our example of finding instances of the word Figure only if they’re followed by a digit, we can use the query Figure(?=sd). Note that we include in the lookahead s (the space after the word Figure) and the digit d. If you try this, you’ll see that Figure is highlighted, but the space and digits are not. This means that whatever we do now applies only to Figure. For example, if you want to italicize these instances of Figure, just set Italics in the Change Format panel. Now you can click Change All (or the more cautious Change and Change/Find) to process all remaining instances. In lookaheads, you can use other GREP constructs as well. Say you want to capture instances of the word Figure not only when they’re followed by a digit, but also by the symbol #, which you use as a placeholder, for instance. This is possible by using the character class [d#], which defines both digits and # as possible characters following Figure: Figure(?=s[d#]). If a character class is not suitable, for example, when you use a multi-character placeholder such as #@#, then you can use alternatives inside the lookahead: Figure(?=s(d|#@#)). Lookahead has a negative counterpart that
lets you match text when it’s not followed by some other text. The format of these so-called negative lookaheads is (?!). For example, to find instances of the word Figure when it’s not followed by a digit, use Figure(?!sd).
Commenting is easier and faster when you're logged in!
Recommended for you
4 Situations Where InDesign Ignores You
Keith is feeling ignored by InDesign today. Discover four situations where InDes...
A Script to Show Options for Placed Files
When you use File > Place you are given a dialog box with a choice to Show Im...
Interview with Russell Viers, Publishing Pro
Q&A with Russell Viers, who is presenting at the The InDesign + Long Documents S...
