Controlling GREP Greediness
Learn how to restrict GREP searches for better targeted results.
This article appears in Issue 72 of InDesign Magazine.
By nature, GREP is greedy. Regular expressions match as much text as possible, regardless of what you intended. If you search for all text within parentheses—using the expression (.+)—you’ll get every character that appears between the very first opening parenthesis in a paragraph through the very last closing parenthesis in that paragraph. That’s fine if there’s only one set of parentheses in the paragraph, but it’s definitely not what you want when there are several sets of parentheses. So how do you rein in GREP’s greediness? The most flexible method is to use the shortest match metacharacter (?) in combination with either the “one or more times” (+) or “zero or more times” (*) metacharacters. So, for example, to find only the text within one set of parentheses, you want to look for an opening parenthesis followed by any character, one or more times, but the shortest match, up to a closing parenthesis: (.+?) The question mark after the plus sign changes its “one or more times” meaning to “one or more times, shortest match,” and the search ends when it reaches the very first closing parenthesis. There are also more precise ways to limit the scope of a search by appending numbers within curly braces to your criteria. You can specify an exact number, or define ranges of “no fewer than” or “no fewer than, but no more than.” For example, to define a U.S. zip code, you could use ddddd, but it’s more efficient to use d{5}, meaning “exactly 5 digits.” To describe “no fewer than 2, but no more than 4,” append the expression {2,4} to your search. To specifiy a minimum, but no maximum (that is, “at least 2”), the expression would be {2,}. Just as with pets, children, and bosses, imposing limits in your
GREP expressions helps you establish an appropriate level of control and achieve much better results.
Commenting is easier and faster when you're logged in!
Recommended for you
Tip of the Week: Organizing Scripts into Folders
There are three new Links panel icons in InDesign CC that you'll see when workin...
Scanning Around With Gene: Mexican Flea Market Art
[Editor’s note: Just hours after this blog post was published, several sha...
Tip of the Week: De-Runt Your Paragraphs With a GREP Style
This InDesign tip was sent to Tip of the Week email subscribers on June 20, 2019...
