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
Mastering Metadata
Learn how to wield the descriptive data embedded in your files to work more effi...
InDesigner: Rolling Stone Magazine
Learn how InDesign is used to produce the most famous music magazine of all.
Building a 3D Scene
When you want to recreate an iconic image with photorealism it’s time to round u...
