XML technologies / Regular expressions / How regex engines work / NFA, DFA and POSIX / POSIX and the leftmost-longest match

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

POSIX explicitly requires that, among matches beginning at the same position, the one matching the most characters must be selected.

The standard says “longest of the leftmost”: the longest match among those starting furthest left. The German translator notes that only the original language is authoritative and therefore places the German rendering “längster frühester Treffer” in quotation marks. POSIX specifies behavior, not implementation. A DFA can readily provide this, but what if a programmer chooses an NFA for other reasons? A POSIX-conforming NFA must match the entire string motorradfahren and all continuation lines, even against an NFA’s natural behavior.

A traditional NFA stops at the first match. What if it also tries every remaining saved state? Whenever such an attempt reaches the end of the regex, it produces another match of the whole expression. After all possibilities have been tried, the longest match is returned. We have a POSIX NFA.

Applied to the first example, an NFA matches ˹(rad)?˼ and saves its state at ˹motor(rad)?▵(radfahren)?˼ in the regex and at motor▵radfahren in the string, knowing a new attempt can start there. A traditional NFA finds the full match motorradfahren, while a POSIX NFA continues trying every variation and eventually reaches motorradfahren .

In Perl, you will learn a trick forcing the traditional NFA of Perl to act like a POSIX NFA and find the longest match (see Finding the leftmost-longest match).

  

 

 

 

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