Members Only

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.

Bookmark
Please login to bookmark Close

Not a member yet?

Get unlimited access to articles and member-only resources with a CreativePro membership.

Become a Member

Comments (5)

Leave a Reply

Your email address will not be published. Required fields are marked *

Loading comments...