XML technologies / Regular expressions / The art of writing regular expressions / backtracking in the larger context
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
Locally, backtracking simply restores an earlier state to try another possibility. Globally, matters are more involved. Here we examine what happens during backtracking, both when a match is found and when the regex fails.
Start by analyzing the examples from Practical regex techniques. Applying the example from Problems caused by greediness, ˹".*"˼, to
Der Name "McDonald’s" wird japanisch "makudonarudo" ausgesprochen
gives the matching process in the figure below.
Figure: successful matching of ˹".*"˼.
The regex is tried at every position, but its first quote fails until position A. There, the whole regex is evaluated. Still, the transmission (see The transmission advances to the next character) knows that after failure, the entire regex must be retried at the next character.
The ˹.*˼ matches to the string's end, where the dot cannot match the nothing at line end. None of the 55 characters consumed is required by the regex; all are optional. For each character matched by ˹.*˼, the engine saves a state to return to if the search fails.
Now that the greedy ˹.*˼ cannot match at the end, the engine restores the last state: “Try ˹".*▵"˼ at position ...ochen▵”.
The closing quote is compared with the string's end. Like the dot, it cannot match nothing, so this fails. Another state is restored, trying the closing quote at ...gesproche▵n, also unsuccessfully.
States saved from A to B are tested in reverse order until C. This state means “Try ˹".▵*"˼ at position ...arudo▵"● ausge...”. The quote and hence the whole regex match, producing a match at D:
Der Name "McDonald’s" wird japanisch "makudonarudo" ausgesprochen
A traditional NFA stops here, discards other saved states, and returns success.
Overtime for the POSIX NFA
A POSIX NFA records the longest match so far and continues. It must test all remaining states for a longer result. We can see none exists, but the engine must blindly try every possibility.
Most states fail immediately; only two other situations match the final quote. The sequences D-E-F and F-G-H resemble B-C-D, but the matches at F and H are shorter than the initial one at D.
At position I, the only remaining option is to advance to the next character. But since a match (three, actually) was found starting at A, the POSIX NFA also finishes, returning the same match.
More work when matching fails
Also consider failure. Use the regex ˹".*"!˼, which cannot fully match our example. Near matches create extra work.
The next figure illustrates this. The sequence A-I resembles the preceding figure, but at D no match is found, since there is no exclamation mark. This sequence applies to both POSIX and traditional NFAs: failure makes even a traditional NFA try every possibility.
Figure: failure with ˹".*"!˼.
With no match starting at A, the transmission advances. Attempts from J, Q and V initially look promising, but become dead ends just as at A. At Y , no further position remains. The entire search fails, after considerable work as the figure shows.
A more restrictive formulation
For comparison, replace the dot with ˹[^"]˼. As noted under How regex engines work, this is more restrictive and produces more predictable results. It is also more efficient: with ˹"[^"]*"!˼ , ˹[^"]*˼ cannot extend beyond the next quote, avoiding many backtracks.
The next figure shows the comparable attempt, which also fails but needs much less backtracking. If this different result is what you want, improved efficiency is a pleasant side effect.
Figure: failure with ˹"[^"]*"!˼.
Alternation can be expensive
Alternation can create substantial backtracking. Return to our makudonarudo string and compare how ˹u|v|w|x|y|z˼ and ˹[uvwxyz]˼ match it. Comparing a class to a character is simple (note: efficiency varies, but a class is always faster than equivalent alternation), so ˹[uvwxyz]˼ requires only transmission backtracking, 41 times, before matching:
Der Name "McDonald’s" wird japanisch "makudonarudo" ausgesprochen
With ˹u|v|w|x|y|z˼, each new start position requires six backtracks before all alternatives fail and the transmission advances. That totals 246 backtracks for the same match. Not all alternations can be replaced, and replacements are not always this simple, but we will learn methods that greatly reduce alternation-related backtracking.
Understanding backtracking is central to NFA efficiency, but it is only one aspect. Internal optimizations in a regex engine can speed searching up enormously . Later we examine the engine's work and its own optimizations.
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