Conditional GREP Expressions
The techniques demonstrated up to now in this Short Cut are all frequently applied. In this section we show a rather less common construct, and though you’ll probably need it less often than the expression types discussed earlier (if at all), it can be useful to have this advanced method 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 or quick]. Some experiments show that including the brackets as optional, \[?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 is a match for the opening bracket”—in other words, a match is made conditional on an earlier match. You can write this as a GREP 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, referred to here by (1)—in other words, if quick is preceded by a bracket—then match a closing bracket now.” If there was no match before quick, a match won’t be attempted ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access