XML technologies / Regular expressions / The art of writing regular expressions / A sobering example

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

We begin with an example dramatically showing the importance of efficiency and backtracking considerations. In Allowing escaped quotes inside quoted strings, we developed the expression ˹"(\\.|[^\\"])*"˼ to find text in quotes while allowing escaped quotes inside. This regex works. With an NFA, however, the alternation applied to every character is very inefficient. For each ordinary character, anything except backslash and quote, the engine must test ˹\\.˼, which fails, then backtrack to find a local match with ˹[^\\"]˼ . For applications where speed matters, making this regex faster would be welcome.

 

A simple change: the best side first

Quoted strings probably contain more ordinary characters than backslash-escaped ones, so reversing the alternatives is natural: test ˹[^\\"]˼ first, and only then ˹\\..˼. Backtracking is then needed only for escaped characters, or when both alternatives fail, since all must be tried before the alternation fails as a whole. The figure illustrates this. Fewer arrows below mean more local matches by the now-first alternative: less backtracking.

Effects of alternative order, traditional NFA

Figure: effects of alternative order, traditional NFA.

When making such a change, ask yourself two questions:

  • Does it affect traditional NFAs, POSIX NFAs, or both?

  • Does it help when a match is found, when none is found, or both?

Think this through carefully and understand Solution 13 before reading on.

Efficient or correct?

When optimizing a regex, you must verify that it remains correct. Alternatives may be reordered only when their order does not matter. The last section had a problem with the incorrect regex ˹"(\\.|[^"])*"˼ (see Allowing escaped quotes inside quoted strings). Its negated class omits backslash, so it matches unintended characters. Testing only data that produces matches will not reveal the problem. Reordering for efficiency makes things worse: with ˹[^"]˼ first, every string with an escaped quote produces a false match:

"Ein 3/4\"-Gewinde."

Ensure correctness first, efficiency second.

 

Allow greediness only locally

In the figure, star causes an iteration for every example. Each character requires a cycle: entering and leaving the alternation and its parentheses. That is much work we would like to eliminate.

With a similar expression, I once discovered an optimization when ˹[^\\"]˼ is the normal case, neither backslash nor quote. With ˹[^\\"]+˼, one iteration reads as many ordinary characters as possible without leaving the parentheses. Without escaped characters, that is the entire string. A match then needs almost no backtracking, and star’s iterations disappear. I was very pleased with myself.

We will examine this more closely later; for now, consider only the statistics. The next figure shows fewer star iterations and backtracks for ˹"(\\.|[^\\"])*"˼, the upper pair. The lower pair shows an even greater gain from combining both changes.

Effects of adding plus, traditional NFA

Figure: effects of adding plus, traditional NFA.

Adding plus made the decisive difference, reducing backtracking and thus star’s cycles. Star quantifies a parenthesized subexpression, so every iteration entails considerable work: saving not only string and regex positions, but also the length of the captured text. We examine this later in the chapter.

This table resembles the one in Solution 13. It has fewer examples but includes the number of star-generated entries into and exits from the parentheses. Each case has slightly more backtracking, but drastically fewer cycles: a major saving.

 

Table: efficiency with a traditional NFA.

  

˹"([^\\"]|\\.)*"˼

˹"([^\\"]+|\\.)*"˼

Sample text

Tests

BT

* cycles

Tests

BT

* cycles

"makudonarudo"

16

2

13

17

3

2

"2\"x3\" likeness"

22

4

15

25

7

6

"sehr...99 Zeichen...lang"

111

2

108

112

3

2

 

Back to reality

Yes, I was very pleased. Unfortunately, this promising improvement is a wolf in sheep’s clothing. While praising it, I deliberately omitted POSIX-NFA figures. You might have been surprised to find, for the example, "sehr●...●lang" three hundred thousand million billion trillion backtracks—324,518,553,658,426,726,783,156,020,576,256 to be exact, about 325 nonillion. To put it mildly, that is A LOT of work. On my machine, it would take about 50 nonillion years, give or take a few hundred trillion millennia. This time is extrapolated from other benchmarks; I did not actually run the tests that long.

Astonishing! How can this happen? In brief, something is quantified directly by plus inside a subexpression quantified by star, with no rule deciding which quantifier handles each subject character. The resulting nondeterminism, this lack of determination, causes disaster. Let me explain.

 

Exponential matching

Without plus, ˹[^\\"]˼ was quantified only by star, and the possible ways for ˹[^\\"]*˼ to match were manageable. It matched one character, then another, and so on, usually many subject characters. Perhaps not the whole string, but even in the worst case, the number of matched characters was proportional to its length. Work also grew linearly with string length.

With the new regex ˹([^\\"]+)*˼, the ways star and plus can divide the string grow exponentially with its length. For the string makudonarudo , there might be twelve star iterations, with each ˹[^\\"]+˼ inside the parentheses matching one character, represented here as ›m a k u d o n a r u d o‹. Or just one star iteration, with the inner ˹[^\\"]+˼ matching the entire string, ›makudonarudo‹? Or three star iterations, with the inner ˹[^\\"]+˼ matching 5, 3, and 4 characters, ›makud ona rudo‹? Perhaps 2, 7, and 3 characters, ›ma kudonar udo‹? Or…

There are many possibilities: 4,096 for this twelve-character string. Each additional character doubles the number, and a POSIX NFA must try them all before answering. This behavior is called exponential or superlinear.

Whatever the name, it means backtracking—a great deal of it! For those interested, the number of backtracking operations for a string of length n is 2n+1, and the required comparisons are 2n+1+2n. With twelve characters, 4,096 combinations take little time, but twenty mean millions and several seconds; thirty mean billions and hours; forty take over a year. Clearly unacceptable.

You may think POSIX NFAs are rare and your traditional NFA makes everything fine. The crucial difference is that a traditional NFA stops on the first overall match. But when no match exists, it too must try every possibility before returning failure. Even the short example "No●\"match\"●here from Solution 13 requires 8,192 combinations before the NFA finally determines that no match exists.

I believed in my discovery so strongly that occasional freezes made me think my tool had a bug. It was simply working on one of these eternal matches. Now that I understand, I include such regexes in my benchmarks to identify engine types:

  • Fast even when no match exists: probably a DFA.

  • Fast only when it matches: a traditional NFA.

  • Always slow: a POSIX NFA.

I say “probably” because optimizing NFAs can recognize exponential patterns and avoid their potentially eternal searches. More on this later, in Detecting excessive backtracking. You will also learn several ways to rewrite such expressions for fast success and fast failure.

This suggests inferring the engine type from relative regex performance. That is exactly what we did with a similar regex in Identifying the regex engine type under How regex engines work.

Not every small change has such catastrophic effects. But without understanding what happens behind the scenes, you grope in the dark until the exceptional case hits. Near this chapter’s end, we examine efficiency and its effects in several examples. Again, the basics must be understood before higher-level issues. Before discussing escapes from eternal matching, I must revisit backtracking in detail.

  

 

 

 

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