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
The CreativePro Guide to Graphics File Formats
Learn about graphics file formats, their pros and cons, and how to choose which...
Spacing Type in InDesign
In the mission to create the best type possible, spacing is the key to success.
Fixing TOC Levels That Refuse to Behave
Learn how text frame options affect the order of items in an InDesign table of c...
