Advanced Techniques

The techniques used in the expressions illustrated in this Short Cut are all frequently applied. In this section we show a rather less common technique, and though you'll probably need it less often than the types of expression discussed earlier (if at all), it can be useful to have these advanced methods in your arsenal. We'll give a few examples.

Suppose you want to match a word, say quick, and, if it occurs in square brackets, those brackets as well. You define this strictly: either two brackets or none. So you want quick and [quick], but not [quick and . . . or pretty quick]. Some experiments show that alternation, \[?quick\]?, isn't any good because it would give you quick with just the opening or the closing bracket as well. So we're looking for something like "match the closing bracket only when there was a match for the opening bracket"—in other words, a match is made conditional on an earlier match. You can write this as a regular expression as follows (the conditional is underlined):

(?x) (\[)? quick (?(\1)\])

What happens is this: with (\[)? we try to match an opening square bracket; the question mark indicates that the expression may or may not match. Then it matches quick. Then follows the conditional: (?(1)\]) paraphrases as "if there was a match for the first capturing parenthesis—in other words, if quick is preceded by a bracket—then try to match a closing bracket now." If there was no match before quick, a match won't be attempted after it. The ...

Get GREP in InDesign CS3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.