XML technologies / Regular expressions / How regex engines work / Backtracking / Two important rules of Backtracking
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
Backtracking is simple in principle, but important subtleties arise in practice. When several options are available, which should the engine try first? When forced to backtrack, which saved option should it try? The first question is answered by this principle:
When there is a choice between trying an option and skipping it, as with quantified subexpressions, an engine using a greedy quantifier will first try the option, while a lazy quantifier will first skip the option.
This rule has far-reaching consequences. It partly explains why quantifiers are greedy. For a full explanation, we must know which of the potentially many saved paths is taken when backtracking begins. Simply put:
When failure triggers backtracking, the most recently saved option is tried. This is LIFO behavior.
The breadcrumb analogy makes this clear: at a dead end, return only to the last breadcrumb. The usual LIFO analogy is a stack, which fits too. The last plate placed on a kitchen stack is also the first removed.
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