XML technologies / Regular expressions / The art of writing regular expressions / Programming techniques for faster expressions / Using atomic groups and possessive quantifiers

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

Atomic groups (see Atomic parentheses) or possessive quantifiers (see Possessive quantifiers) can often improve speed substantially, provided they do not change the matches. For example, if the engine applying ˹^[^:]+:˼ fails to find the final colon, any backtracking is pointless: the consumed characters cannot contain colons, or the earlier part of the regex, ˹[^:]+˼ would already have failed. Atomic parentheses ˹^(?>[^:]+):˼ or a possessive quantifier can therefore be used safely, discarding all saved states created by the plus. This leaves no states for backtracking and avoids all these futile attempts. The box Automatic possessification explains that a sufficiently smart regex engine can detect this automatically.

Nevertheless, misuse of these constructs can produce incorrect matches or prevent matching altogether, so use them carefully. Replacing ˹[^:]˼ with a simple ˹^.*:˼, as in ˹^(?>.*):˼, guarantees failure. The ˹.*˼ consumes the whole line, including any colons. Nothing remains for the following ˹:˼, and the atomic group prevents reclaiming any characters.

  

 

 

 

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