XML technologies / Regular expressions / The art of writing regular expressions / Programming techniques for faster expressions / Greedy or lazy?

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

The task usually determines whether quantifiers must be greedy or lazy. For example, ˹^.*:˼ differs greatly from ˹^.*?:˼. The first matches through the last colon, the second only through the first. If other knowledge guarantees exactly one colon, they are effectively equivalent, matching everything through that colon, so we can choose the faster version.

The faster version is not always obvious. A lazy quantifier finds a colon near the start of a long string faster; a greedy one is faster when it is near the end. With no knowledge beyond the single-colon constraint, greedy is usually faster, especially when optimization based on the character following a lazy quantifier (see The character following a lazy quantifier) cannot be used.

For shorter strings, the situation is even less clear. Optimization matters less, but if maximum performance is essential, benchmark both versions on representative data.

A similar question arises when choosing between a lazy quantifier and a negated character class. ˹^.*?:˼ and ˹^[^:]*:˼ have the same effect, but which is faster? This again depends on the data and language. Usually the negated class is much faster than the lazy construct. In Perl, optimization based on the character following a lazy quantifier applies, reversing the result.

  

 

 

 

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