XML technologies / Regular expressions / The art of writing regular expressions / Unrolling the loop.

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

The greatest performance improvements to a regex often have nothing to do with internal optimizations. They often become possible when we understand exactly how the regex engine works and can thus help it find a match. We have examined enough details; now let us apply what we have learned on a larger scale. A technique I call “loop unrolling” (loop unrolling) can make certain regular expressions much faster. For example, we can transform the interminable matching at the beginning of this chapter (see Back to reality) into a regex that detects failure in a reasonable time and, as a bonus, is faster when successful too.

The “loop” in question is the one implicitly introduced by a star when the expression has the general form ˹(dies|das|...)*˼. Indeed, this is the structure of our “eternal match” ˹"(\\.|[^\\"]+)*"˼. Given that this expression takes roughly forever to discover that no match is possible, a little speed improvement could be quite welcome.

There are two competing approaches:

  1. We can examine which parts of ˹(\\.|[^\\"]+)*˼ actually match something in a set of test cases. This gives us subexpressions from which we can assemble a more efficient regular expression.

    In my mind’s eye, I see a large ball rolling over text, representing the regex ˹(...)*˼. The matching parts inside the parentheses (...) leave a trail of used subexpressions, like a dirty ball on a carpet.

    The analogy is a little far-fetched, I know.

  2. The second approach considers the expression from a higher level. We make informed assumptions about what matching text is likely to look like and formulate a more efficient expression accordingly.

Both approaches must, of course, preserve the expression’s behavior. I begin with loop unrolling, then transfer the resulting insights to the second approach.

To keep the following examples from becoming cluttered with punctuation, I always use ˹(...)˼ for grouping. If noncapturing groups using ˹(?:...)˼ are supported, the expressions become even more efficient. Later, we also examine the effect of atomic groups (see Atomic groups) and possessive quantifiers.

  

  

 

 

 

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