XML technologies / Regular expressions / How regex engines work / More on greediness / Problems caused by greediness

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

The last example showed that ˹.*˼ first proceeds to the line’s end, or the string’s end if dot matches newlines, even across logical lines. This happens because ˹.*˼ greedily takes everything it can and gives back characters only when a later part of the regex needs them for the whole expression to match.

This can be troublesome. To match text inside double quotes, you might first write ˹".*"˼. Knowing what we do about ˹.*˼, guess the result for this string:

Der Name "McDonald's" wird japanisch "makudonarudo" ausgesprochen

You need not guess: you know enough about matching. After the opening quote, ˹.*˼ matches every character through the string’s end. During subsequent Backtracking, it retreats, or rather is pushed back by the engine only as far as required for the whole expression to match: the last quote. Thus it matches

Der Name "McDonald's" wird japanisch "makudonarudo" ausgesprochen

, hardly the intended quoted string. This is one reason I warn against overusing ˹.*˼ : it can produce unexpected results.

How can we match only "McDonald's"? We want not anything between quotes, but anything except a quote. Using ˹[^"]*˼ instead of ˹.*˼ prevents overshooting.

The basic behavior of the regex engine with ˹"[^"]*"˼ is unchanged. After the opening quote, ˹[^"]*˼ can match as many characters as it wants, here up to the quote after McDonald's, ˹[^"]˼ cannot match that quote. The engine passes control to the regex’s third element, the closing quote, which matches it exactly. The result is now correct:

Der Name "McDonald's" wird japanisch "makudonarudo" ausgesprochen

One unexpected difference remains possible: in most dialects, ˹[^"]˼ matches newlines, unlike dot. To prevent matches spanning lines, use ˹[^"\n]˼.

  

 

 

 

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