XML technologies / Regular expressions / The art of writing regular expressions / Common optimizations
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
A good regex implementation knows several ways to reach a result faster, whether success or failure. There are two classes of optimizations:
Doing work faster
Some subexpressions, such as
˹\d+˼, occur so often that the engine handles them with specialized code, faster than its general-purpose machinery.
Avoiding work
An engine may save time by skipping parts of a regex that do not affect the result, or need not be applied to the whole subject. For example, a regex beginning with
˹\A˼(start of string) need be tried at only one position. If it fails there, the transmission need not advance character by character.
Below we examine several optimizations I have encountered, some very sophisticated. No language combines them all, and no two use exactly the same set. Others are surely possible; this chapter should help you exploit those your language provides.
Nothing comes free!
Optimizations can save time, but only when the saving exceeds their own cost. Checking for an optimization that cannot be used makes the result arrive slower because of wasted overhead. The engine must balance cost, benefit, and applicability.
Consider the expression ˹\b\B˼ (word boundary at the same position as a non-word boundary) can never match. If a regex engine can determine that every possible candidate requires ˹\b\B˼, it knows the entire regex can never match. It need not run it at all: immediate failure would save enormous time on long subjects.
Yet no implementation I know detects this. Why? Determining whether this subexpression participates in every possible match is not easy. A regex may contain ˹\b\B˼ somewhere and still match, so the optimizer must analyze it carefully.
The potential saving is considerable; if ˹\b\B˼ were common, the work would be worthwhile.
But this subexpression is so rare and nonsensical (note: I formerly used ˹\b\B˼ inside larger expressions to force a branch to fail. For example, inserting it at the marked position in ˹...(dies▵|dieses andere)...˼ makes the first alternative impossible. Nowadays I normally use ˹(?!)˼ for this purpose. An interesting, though Perl-specific application appears under Using code patterns to list all possible matches) that even enormous savings would rarely be realized.
Everyone does it differently
Keep in mind that although I give techniques simple names, each implementation differs internally. Even a seemingly harmless regex change can dramatically speed up one implementation while slowing down another.
How a regular expression is applied
Before further optimizations, understand the search steps. We have studied backtracking in detail; now step back to consider the entire process.
Applying a regex to a subject involves these steps:
Compiling the regex
Check syntax and, if valid, compile to an internal form.
Starting the transmission
The transmission starts the engine at the subject's first position, the beginning of the string.
Testing components
The engine works through the regex and subject component by component, as described under How regex engines work. Beyond the backtracking details already discussed, note:
Adjacent components, such as
˹S˼, ˹u˼, ˹b˼, ˹j˼, ˹e˼ ..., are tried in sequence, stopping at the first failure.Quantifiers alternate between testing the quantifier (should another repetition be attempted?) and its component (does it match?).
Capturing groups require bookkeeping: text is saved for later use in variables such as
$1. Since captures are subject to backtracking, engine state must also be saved when entering and leaving groups.
Finding a match
A traditional NFA finishes successfully at its first match. A POSIX NFA records the longest match so far, but must still examine every saved state for longer matches. Once those states are exhausted, it returns the longest match.
Advancing the transmission
If the current position fails, the transmission advances to the next position, where the engine repeats step 3.
Failure
If no position succeeds, the entire regex fails.
The next sections examine optimizations that reduce work at these stages.
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