XML technologies / Regular expressions / How regex engines work / Pattern-matching basics / Rule 2: Standard quantifiers are greedy
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
Matching has been simple so far, but dull: without stars, plus signs, alternation, and other metacharacters, you cannot do much. Understanding these requires more background.
First, standard quantifiers are (?, *, +, {min,max}) greedy. A quantifier applied to a subexpression, such as a in ˹a?˼, ˹(expr)˼ in ˹(expr)*˼, or ˹[0-9]˼ in ˹[0-9]+˼, has minimum and maximum match lengths. These quantifiers always try to match as much text as possible. (Some dialects also have other quantifier types, not discussed here.)
In other words, standard quantifiers accept the minimum only when forced. Otherwise, they take as many characters as allowed. They accept less only if later parts of the regex would otherwise fail. For example, ˹\b\w+e\b˼ finds words ending in e, such as Programme. The ˹\w+˼ alone would consume the entire word, leaving nothing for the final e. For overall success, ˹\w+˼ must settle for Programme, allowing ˹e\b˼ and hence the entire regex to match.
A greedy quantifier may even match nothing, if allowed by a star, question mark, or interval {0,max}. But only later regex components force this. By default, quantifiers seek more than the minimum, hence “greedy.”
Greediness has many useful and occasionally annoying effects. It explains why ˹[0-9]+˼ matches the whole number in März●1998. After finding 1, plus has met its minimum, but greedily seeks more, also matching 998. The match ends at the string's end, where ˹[0-9]˼ cannot match.
A subject example
This applies beyond numbers. To check whether an email header line is the subject, as in an earlier chapter (see A small mail program), simply use ˹^Subject:●˼. With ˹^Subject:●(.*)˼, you can later retrieve the subject from the captured data, for example with $1 in Perl. (Note: capturing groups make this example NFA-specific; only NFAs support them. The point about greediness applies to all engine types.)
Before asking why ˹.*˼ matches the whole subject, note that the regex has already succeeded as a whole. ˹^Subject:●˼ has matched, and nothing follows that could jeopardize success. ˹.*˼ will always match, because matching nothing satisfies the star.
Why include ˹.*˼ if it does not affect success? Because the greedy star applies the dot as often as possible, which fills $1. Parentheses do not affect matching logic. When ˹.*˼ reaches the end, no characters remain for the dot. The quantifier stops and yields to later elements, which might still match even though the dot cannot. Here none follow, so the regex engine knows a match has been found.
Too greedy
What if we add a second ˹.*˼: ˹^Subject:●(.*).*˼? Nothing changes. The first ˹.*˼ inside parentheses greedily consumes the entire subject, leaving the second ˹.*˼ nothing. That is fine: a star can accept nothing. If the second ˹.*˼ were captured, its corresponding $2 would always be empty.
Does this mean nothing can ever match after ˹.*˼? Of course not. As in the example with ˹\w+e˼, later components can force greedy quantifiers to give characters back for overall success.
The expression ˹^.*([0-9][0-9])˼ finds the final two digits anywhere in the string and captures them in $1. Initially, ˹.*˼ consumes everything. But the following ˹([0-9][0-9])˼ is required , effectively saying, “You took too much! Give something back so I can match.” Greedy components take as much as possible, but submit to overall success, reluctantly and only when forced.
Applying ˹^.*([0-9][0-9])˼ to ›etwa●20●Zeichen●lang‹ makes ˹.*˼ again consume the whole string. But the first ˹[0-9]˼ seeks a digit, reclaiming the ›g‹ last consumed. That fails, so ˹.*˼ must return another character, the n in lang. This repeats twelve more times until the digit 0 is matched.
The first ˹[0-9]˼ is satisfied, matching a digit, 0, but the second is not. The ˹.*˼ must return still more characters for overall success. Now 2 is matched by the first ˹[0-9]˼; the 0 is released for the second ˹[0-9]˼, the whole expression matches ›etwa●20●Zeichen...‹, and $1 receives ›20‹.
First come, first served
We might try capturing the whole final run of digits instead of just the last two: ˹^.*([0-9]+)˼. Applying this regex to ›Copyright 2003.‹, what do the parentheses capture? See the answer under Solution 17.
The finer details
A clarification: phrases like “ ˹.*˼ must give back …” or “˹[0-9]˼ forces …” are slightly misleading. They are convenient and describe the result accurately, but what happens internally depends on whether the engine is a DFA or NFA. It is time to examine that distinction.
German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln