XML technologies / Regular expressions / How regex engines work / More on greediness / Greediness, laziness and Backtracking: the essentials
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
In Greedy or lazy — finding a match comes first you learned that the presence of greedy or lazy elements in a regex is not all that matters: finding a match comes first. Even if a greedy construct must surrender characters or a lazy one must accept more, a local failure makes the engine try every saved state, retracing the breadcrumbs and exploring untried paths. Greedy or not, the engine tries every possible path before giving up and reports failure.
Greedy and lazy cases try paths in different orders, which is why both exist. If neither finds a match, however, both have tried exactly the same paths.
If a search has exactly one possible match, both greedy and lazy regexes find it, but try unsuccessful paths in different orders. Greediness then affects how the match is found rather than which match is found, an efficiency issue discussed in The art of writing regular expressions.
If multiple matches are possible, greedy and lazy constructs select different valid matches. The example using ˹".*"˼ has three possible matches:
Der Name "McDonald's" wird japanisch "makudonarudo" ausgesprochen
Der Name "McDonald's" wird japanisch "makudonarudo" ausgesprochen
Der Name "McDonald's" wird japanisch "makudonarudo" ausgesprochen
Expression ˹".*"˼ with a greedy star produces the longest match; ˹".*?"˼, the lazy quantifier, produces the shortest.
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