XML technologies / Regular expressions / The art of writing regular expressions / Programming techniques for faster expressions / Exposing anchors

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

Optimizations exploiting anchors (˹^˼, ˹$˼, ˹\G˼ and so on) are among the most effective. They tie the match to a particular input position. Some regex engines do not readily recognize this anchoring, but we can help them.

Factoring ^ or G to the start of an expression

Expressions ˹^abc|^123˼ and ˹^(?:abc|123)˼ are logically equivalent, but many engines cannot identify the line-anchor optimization in the first (see Line- and string-anchor optimizations). The second helps the engine. PCRE and all applications using it recognize both cases; most other NFA tools recognize only the second.

A similar difference appears with ˹(^abc)˼ and ˹^(abc)˼. The first offers no advantage: it actually hides the anchor and incurs capturing-group overhead from the start. Some systems, including PCRE, Perl and the .NET languages, recognize both forms; others, such as Ruby and Sun’s Java regex package, recognize only the factored form.

In Python, anchor optimizations seem absent, so these techniques do not apply. Most manual optimizations are irrelevant to Tcl anyway; see the box DFAs, Tcl and regex tuning.

 

Factoring $ to the end of an expression

The principle is the same as above: ˹abc$|123$˼ and ˹(?:abc|123)$˼ are logically identical but treated differently by optimizers. Among current tools, only Perl differs, because only it implements the end-anchor optimization (see End-of-string or end-of-line anchor optimization). With ˹(...|...)$˼, the optimization applies; with ˹(...$|...$)˼, it does not.

  

 

 

 

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