XML technologies / Regular expressions / How regex engines work / backtracking / backtracking and greediness

(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)

In tools using this kind of regex-directed NFA, understanding backtracking is essential for writing regexes that work correctly and quickly. We have examined greedy behavior with ˹?˼; now consider the greediness of star and plus.

 

Backtracking with star and plus

Consider the regex ˹x*˼ as roughly equivalent to ˹x?x?x?x?x?x?...˼, or better, ˹(x(x(x(x...?)?)?)?)?˼. Remember that outward regex form hardly matters to a DFA: all three forms are identical. This is similar to what we just examined. Before trying the star-quantified component, the engine saves its state for a later failure. It repeats this until a star-initiated attempt fails.

Following ˹[0-9]+˼ applied to ›eine●1234●Zahl‹, we find that ˹[0-9]˼ fails after the 4. Four states have been saved, giving the engine four positions where it can return and resume searching:

eine 1▵234 Zahl 
 eine 12▵34 Zahl 
eine 123▵4 Zahl 
eine 1234▵ Zahl 

These four states exist because trying ˹[0-9]˼ is optional at those positions. When matching fails at the space, the engine returns to its latest saved state and resumes at ›eine●1234▵●Zahl‹ in the text and ˹[0-9]+▵˼ in the regex. That is the regex’s end, though the engine only now realizes it. The entire expression has been traversed, so matching is complete and successful.

The list omits position ›eine●▵1234●Zahl‹ because the first digit is mandatory with plus. Would this position be included with ˹[0-9]*˼? (Beware, trick question!) See Solution 11.

Revisiting a larger example

With this deeper understanding, revisit the ˹^.*([0-9][0-9])˼ example (see Too greedy). Instead of simply saying greediness causes the result, we can explain it precisely through NFA mechanics.

Use ›CH-8032●Zürich‹ as an example. Once ˹.*˼ reaches the string end successfully, fourteen states remain, one for each position where dot-star matched an optional, potentially unnecessary character. These states let the engine resume at ˹^.*▵([0-9][0-9])˼ in the regex and at any of fourteen string positions.

At the string end, we try the first ˹[0-9]˼, which cannot match. No problem: saved states remain, more than a dozen. Backtracking restores the last, immediately before ˹.*˼ matched the final h. Undoing this local match leads to testing ˹[0-9]˼ against h, which fails.

This backtrack-and-test cycle continues until reaching 2; then the first ˹[0-9]˼ matches, but the second fails, requiring more backtracking. It no longer matters that the first ˹[0-9]˼ just matched: backtracking restores a state before the first ˹[0-9]˼. That state is also immediately before 3, so the first ˹[0-9]˼ matches again. This time the second also matches 2. The entire match is therefore ›CH-8032●Zürich‹, and the variable $1 receives 32.

Some observations: backtracking saves not only regex and text positions, but also each capture’s state and text so everything can be restored. Here, every backtrack returned to ˹^.*▵([0-9][0-9])˼, which, for matching, is equivalent to ˹^.*▵[0-9][0-9]˼. But entering and leaving capturing groups while moving through the regex matters: each time, the value ultimately determining $1 must be maintained, affecting overall efficiency.

One last point, perhaps already obvious: star and other greedy quantifiers initially consume as much as possible, regardless of what follows in the regex. Here, at ˹.*˼, the engine does not know to stop at the first digit, penultimate digit, or anywhere else. It blindly finds matching characters until dot finally fails. We saw this when the ˹[0-9]+˼ part of ˹^.*([0-9]+)˼ never matched more than one digit (see Too greedy).

  

 

 

 

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