XML technologies / Regular expressions / PHP / Recursive regular expressions

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

Almost every aspect of the regex dialect of PHP has been covered generally under Features and dialects, but one unique surprise remains: recursive regexes.

The sequence ˹(?R)˼ means apply the whole regex recursively here, while ˹(?num)˼ means apply subexpression number num recursively here. Named captures provide a variant of the second form using ˹(?P>name)˼.

The following sections show applications. Recursion also matters in the larger XML-tag example under Checking correct tag nesting.

 

Parsing text with nested parentheses

Arbitrarily nested parentheses are the classic application of recursive regexes. One approach is: ˹(?:[^()]++|\((?R)\))*˼.

This regex matches any number of either alternative. The first, ˹[^()]++˼, matches anything except parentheses. Its + is possessive; otherwise, the outer ˹(?:...)*˼ could cause interminable matching (see Back to reality).

The other branch, ˹\((?R)\)˼, is interesting: it matches parentheses containing arbitrary text, provided nesting is correct. That content is exactly what the entire regex matches, so ˹(?R)˼ recursively applies the current regex to it.

This works well, but extend it carefully: every addition is recursively applied whenever ˹(?R)˼ is reached.

To validate an entire string’s nesting, you might wrap the regex in ˹^...$˼ to force a full-string match. That is wrong: the added anchors could never match inside a recursive call.

 

Recursing with numbered groups

The construct ˹(?R)˼ refers to the whole regex. With ˹(?num)˼, only group number num is used for recursion. Strictly, ˹(?num)˼ need not be a recursive call: the construct ˹(?num)˼ need not itself be inside group number num; it can occur outside that group too.

Since group zero is the whole regex, ˹(?0)˼ is equivalent to ˹(?R)˼.

This solves the earlier problem: first enclose the regex in parentheses, then add the anchors ˹^...$˼. Replace ˹(?R)˼ with ˹(?1)˼ for recursion. Only the newly added outer group recurses, excluding the anchors: ˹^((?:[^()]++|\((?1)\))*)$˼

The underlined part is the first group’s contents, applied recursively whenever ˹(?1)˼ is reached.

The following fragment reports whether the text in $text has correctly nested parentheses:

if (preg_match('/^ (  (?: [^()]++ | \( (?1) \)  )*  ) $/x', $text))
   echo "Korrekte Klammern\n";
else
   echo "Fehlerhaft verschachtelte Klammern\n";

 

Recursing with named groups

If the recursive subexpression is enclosed in a named group (see Named subexpressions), use (?P>name) instead of (?num). The example becomes:

˹^(?P<krempel>(?:[^()]++|\((?P>krempel)\))*)$˼

This is complicated, but the x modifier improves readability (see Pattern modifiers):

$pattern = '{
    # Regex beginnt hier ...
    ^
      (?P<krempel>
          # Alles innerhalb dieses Klammerpaars nennen wir »krempel«.
          (?:
              [^()]++              # Alles außer Klammern.
            |
              \(  (?P>krempel)  \) # Öffnende Klammer, »krempel«, schließende Klammer.
          )*
      )
    $
    # ... hier endet die Regex.
}x'; # Das 'x' ist der Modifikator »Freie Form«.

if (preg_match($pattern, $text))
   echo "Korrekte Klammern\n";
else
   echo "Fehlerhaft verschachtelte Klammern\n";

 

More on possessive quantifiers

One more point about possessive quantifiers: if the outer group’s star ˹(?:...)*˼ were possessive, the second ›+‹ in ˹[^()]++˼ could be omitted. At least one quantifier must be possessive to avoid interminable matching. Without possessive quantifiers or atomic groups (see Using atomic groups and possessive quantifiers), remove the first branch’s quantifier: ˹(?:[^()]|\((?R)\))*˼

This is less efficient but avoids interminable matching. Speed improves again by unrolling the loop using the technique in The art of writing regular expressions (see Unrolling the loop), giving: ˹[^()]*(?:\((?R)\)[^()]*)*˼

 

No backtracking into recursion

PHP’s preg dialect treats recursive subexpressions as atomic groups (see Using atomic groups and possessive quantifiers). If a recursive group matches text that backtracking would need to partially return for overall success, the result is failure instead.

Partially is important: backtracking can return the entire text matched by a recursive group. Only returning to a position partway inside the recursive call is forbidden.

 

Finding a nested parenthesized group

We have checked complete lines for correct nesting. For completeness, this regex finds a parenthesized group that may itself contain nested groups: ˹\((?:[^()]++|(?R))*\)˼

It uses the same ingredients in a different arrangement. As part of a larger regex, enclose it in parentheses and replace the full-regex recursion ˹(?R)˼ with ˹(?1)˼, or the appropriate group number.

  

 

 

 

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