Limiting Matches with GREP in InDesign
Peter Kahrel shares a technique for targeting a specific instance in a repeating pattern of text.

Copyeditors dread bibliographies, especially if a publisher insists on their own format. That insistence can easily lead to many repetitive corrections that numb both the mind and the fingers. But we can use that repetitiveness to our advantage, because where there’s a consistent pattern of errors, there’s an opportunity to fix them with GREP.
One type of correction that regularly occurs is the use and placement of parentheticals, such as publication years and names of publishers. These are often wrong, and in order to fix them, we typically need to find just the first parenthetical in a paragraph or only the last one. But GREP expressions are gluttons—they want to consume as much content as possible—so if you look for something like (.+?)
, you end up with all parentheticals. If you want to match just the first, or just the last, parenthetical, you need to take some special measures.
To find only the first parenthetical in a paragraph, the idea is to look for an opening parenthesis which has no other opening parenthesis between it and the beginning of the paragraph. This GREP expression does that: ^.*?K(.+?)
. The expression works as follows: from the start of the paragraph (^
), we match any sequence of characters (.*
) until we hit the first opening parenthesis. Then we discard whatever we matched so far: that’s what K
, the magnificent and only recently discovered modifier, does (see InDesign Magazine 73). From there, we match up to the next closing parenthesis. Because the part between the beginning of the paragraph and the first opening parenthesis is discarded, we in effect match just the first parenthetical.
Matching only the last parenthetical in a paragraph is in a way the mirror image of matching only
the first one: find a parenthetical such that there is no opening parenthesis between the matched closing parenthesis and the end of the paragraph: ([^)]+)(?=[^(]+$)
. The first part of the expression, ([^)]+)
, matches a parenthetical. The part of the expression that ensures that we match just the last parenthetical is (?=[^(]+$)
, which reads “from here to the end of the paragraph, and no character is (
.”
Commenting is easier and faster when you're logged in!
Recommended for you

Illustrator Downloadable: Tropical Shadow Overlay Kit
Downloadables are an exclusive benefit for CreativePro members! (Not a member ye...

Illustrator Downloadable: Summer Citrus Pattern Set
Downloadables are an exclusive benefit for CreativePro members! (Not a member ye...

InDesign Downloadable: Tables SuperGuide
Downloadables are an exclusive benefit for CreativePro members! (Not a member ye...