XML technologies / Regular expressions / Perl / Unusual uses of Perl’s regex extensions / Matching nested constructs with code patterns

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

The example in Matching nested pairs with dynamic regexes showed how to match nested parentheses using a dynamic regex construct. That is generally easiest, but code patterns work too.

The approach is simple: count opening and closing parentheses, allowing a closing one only when openings remain. We count inside code patterns, but first consider this not-yet-functional regex skeleton:

my $VerschachtelteInnereien = qr{
  (?>
    (?:
       # Weder öffnende noch schließende Klammern
        [^()]+
       # Öffnende Klammer
       |  \(
       # Schließende Klammer
       |  \)
    )*
  )
}x;

Atomic grouping improves efficiency, preventing ˹([...]+|...)*˼ from causing endless matching (see Back to reality) when $VerschachtelteInnereien appears in an expression that can trigger Backtracking. Applying m/^\( $VerschachtelteInnereien \)$/x to ›(hier● fehlt● die● schließende● Klammer‹ would make the regex engine spend a long time advancing and retreating within $VerschachtelteInnereien without the atomic group eliminating unnecessary saved states.

Counting parentheses takes four steps:

  1. First initialize the counter to zero:

    (?{ local $OffeneKlammern = 0 })

  2. On an opening parenthesis, increment the counter to record the required number of closings:

    (?{ $OffeneKlammern++ })

  3. On a closing parenthesis, decrement only if the pending count is positive. Zero means more closings than openings; use ˹(?!)˼ to fail:

    (?(?{ $OffeneKlammern }) (?{ $OffeneKlammern-- }) | (?!) )

    This uses a ˹(? if then|else)˼ construct (see Conditional regular expressions) with the code pattern in the condition.

  4. At the end, verify the counter is zero. Otherwise, too few closings were found, which is an error:

    (?(?{ $OffeneKlammern != 0 })(?!))

Insert these elements into the skeleton:

my $VerschachtelteInnereien = qr{
  (?{ local $OffeneKlammern = 0 }) #  1. Zählt die offenen bzw. noch zu schließenden Klammern.
  (?> # Atomare Gruppe ist effizienter
     (?:
        # Weder öffnende noch schließende Klammern
          [^()]+
        # 2.  Öffnende Klammer
        |  \(  (?{ $OffeneKlammern++ } )
        # 3.  Schließende Klammer erlauben, wenn noch Klammern offen sind
        |  \)  (?(?{ $OffeneKlammern != 0 }) (?{ $OffeneKlammern-- }) | (?!) )
     )*
  )
  (?(?{ $OffeneKlammern != 0 })(?!)) #  4. Fehlschlag, falls am Ende noch Klammern offen sind.
}x;

This regex can now replace $Tiefe_N from Matching nested pairs with dynamic regexes.

Declaring $OffeneKlammern with local is merely a precaution in case the global variable is used elsewhere. Unlike the preceding section’s local variables, backtracking is not a problem here: the variable appears inside an atomic construct, so a matched alternative cannot be surrendered. Atomic grouping therefore not only improves efficiency but ensures counter $OffeneKlammern always equals the number of parentheses actually matched.

  

 

 

 

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