GREP of the Month: Positive Lookbehind
They say you should never look back, but this amazing GREP expression proves them wrong!
This article appears in Issue 63 of InDesign Magazine.
One of the most common ways to find text is based on other text that comes before or after it. For example, “only find numbers that come after a dollar symbol.”
It’s easy to find the dollar symbol and the number, you’d just use the code \$\d+ (“find a dollar symbol followed by one or more digits”). However, if you want to find “any numbers that follow a dollar symbol” (that is, the numbers but not the currency), you need to use a code based on something called the “positive lookbehind.” To get this, you first type (?<=) and then insert one or more characters after the = symbol. In this instance, the expression is (?<=\$) \d+ InDesign says “I’ll look for any series of digits, but only if it comes after a dollar sign.”
Here’s another way you can use the positive lookbehind. This code:
(?<=\d)(rd|nd|th|st)
will find st, rd, or th ordinals (such as 1st, 2nd, 3rd) that follow a digit, so that you can apply a superscript to just the ordinal and not the digit.
Note that the code after the = symbol must specify an exact number of characters. That is, you might expect the expression (?<=+) \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.
Commenting is easier and faster when you're logged in!
Recommended for you
LiveDocs Help Pages Come to InDesign CS3
About a month ago I wrote here about some powerful new Help features in InDesign...
MoMA Online Courses
If your New Year’s resolution was to learn more about art in 2014, an online cou...
Album Moxie: The Savvy Photographer’s Guide to Album Design and more—with InDesign
There’s an old saying that when all you have is a hammer, everything looks...
