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
Making Catalogs that Work (with Less Work)
Transform your catalog designs from ho-hum to high performing with these tips.
Designing Book Covers in InDesign
Learn how the key to designing a book jacket lies in the execution of the InDesi...
InDesigner: LensWork
A look at LensWork, a magazine devoted to black and white photography, is produc...
