XML technologies / Regular expressions / How regex engines work / More on greediness / Is alternation greedy?
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
How alternation works is an important point, because it differs greatly between the two types of regex engine. When alternation is reached, any of its alternatives may match the string, but which is chosen? In other words, if several alternatives can match, which wins? Does the longest always win? Then alternation is greedy. Or does the shortest win? Then it is lazy. Or does neither win?
First consider a traditional NFA engine such as those of Perl, Java, PHP, the .NET languages and many others (see Types of regex engines). In an alternation, the alternatives are tried in sequence, from left to right as written in the regex. When alternation is reached in the example ˹^(Subject|Date):●˼, the first alternative is tried, ˹Subject˼. If it matches, the remainder of the regex is applied. If it fails and other alternatives exist (here ˹Date˼), the regex engine uses Backtracking to return and try the next alternative. This is simply another case of the engine backtracking to a state where untried possibilities remain. This repeats until either an overall match is found or all possibilities (here, alternatives) have been exhausted.
What text does a traditional NFA find with the expression ˹zucker|zu|zuckerhut˼ when given the string ›den●zuckerhut●besteigen‹? The alternatives are tried and initially fail at each character position in the string. Only when the transmission advances and starts an attempt at ›den●▵zuckerhut●besteigen‹ does the first alternative, ˹zucker˼, match. Since alternation is the last element of the regex, matching ends here. The other alternatives are never even tried.
Alternation is therefore neither greedy nor lazy, but ordered: it follows the order of alternatives in the regex, at least with a traditional NFA. This is more flexible than greedy behavior, since it gives us more control over matching. The programmer can specify: “Try this, then that, and finally this other possibility, until a match is found.”
Not all dialects have this ordered alternation. In DFAs and POSIX NFAs, alternation is greedy: among several matching alternatives, the one matching the longest substring is followed (here ˹zuckerhut˼). In Perl, PHP, all .NET languages, java.util.regex and every other system with a traditional NFA (see the table Programs and their regex engine types), alternation is ordered.
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
back to top