XML technologies / Regular expressions / Perl / Unusual techniques with Perl regex extensions / Matching nested pairs with dynamic regular expressions
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
Dynamic constructs mainly recognize arbitrarily deep nesting of bracket-like structures, once seemingly impossible with regexes. The classic example is matching arbitrarily nested parentheses. To appreciate why this is exciting, first consider why ordinary regexes cannot do it.
This simple regex matches parenthesized text: ˹\(([^()])*\)˼. It permits neither opening nor closing parentheses inside, so no nesting: a maximum depth of zero. We can wrap it in a regex object and use it as follows:
my $Tiefe0 = qr/ \( ( [^()] )* \) /x; # Geklammerter Text.
.
.
.
if ($text =~ m/\b( \w+$Tiefe0 )/x) {
print "Funktionsaufruf gefunden: $1\n";
}This recognizes a function call such as “substr($str, 0, 3)”, but not “substr($str, 0, (3+2))”, which contains nested parentheses. Let us extend the regex to permit one level of nesting.
We want parenthesized text inside the outer parentheses. Extend the inner subexpression, previously ˹[^()]˼, by adding a subexpression matching parenthesized text. That is exactly what our newly created object $Tiefe0 does. We can thus construct a depth-one regex:
my $Tiefe0 = qr/ \( ( [^()] )* \) /x; # Geklammerter Text.
my $Tiefe1 = qr/ \( ( [^()]| $Tiefe0 )* \) /x; # Verschachtelungstiefe Eins.The regex $Tiefe0 is unchanged. From it, we build $Tiefe1, which recognizes its own parentheses plus the parentheses from $Tiefe0, giving depth one.
Repeating the recipe produces the next level, $Tiefe2, built from $Tiefe1, itself built from $Tiefe0:
my $Tiefe0 = qr/ \( ( [^()] )* \) /x; # Geklammerter Text.
my $Tiefe1 = qr/ \( ( [^()] | $Tiefe0 )* \) /x; # Verschachtelungstiefe Eins.
my $Tiefe2 = qr/ \( ( [^()] | $Tiefe1 )* \) /x; # Verschachtelungstiefe Zwei.We could continue forever:
my $Tiefe3 = qr/ \( ( [^()] | $Tiefe2 )* \) /x; # Verschachtelungstiefe Drei.
my $Tiefe4 = qr/ \( ( [^()] | $Tiefe3 )* \) /x; # Verschachtelungstiefe Vier.
my $Tiefe5 = qr/ \( ( [^()] | $Tiefe4 )* \) /x; # Verschachtelungstiefe Fünf.
...The following figure illustrates the first few nesting levels.
Figure: Regexes for different nesting depths.
The expanded expressions for each level are interesting to inspect, for example $Tiefe3:
\(([^()]|\(([^()]|\(([^()]|\(([^()])*\))*\))*\))*\)Not a pretty sight.
Fortunately, we need not struggle through this; that is the engine’s job. The Tiefe variables work for a fixed depth, but not for arbitrary nesting. If we allow depth X, Murphy’s law guarantees data nested X+1 levels deep.
Dynamic constructs can achieve this. Observe that every $Tiefe variable after the first is built identically: for another nesting level, include the previous line’s variable. If all lines are essentially identical, perhaps they could include themselves. That would handle every depth.
Dynamic constructs make exactly this possible. When building an object like the $Tiefe variables, we can reference it from code inside the regex. The construct can contain any Perl code whose result is interpretable as a regex; here it simply returns an existing regex object. With our $Tiefe style object in $Tiefe_N, access it with ˹(??{$Tiefe_N})˼:
my $Tiefe_N; # Muss vordeklariert sein, weil es in seiner eigenen Definition verwendet wird.
$Tiefe_N = qr/ \(( [^()] | (??{ $Tiefe_N }) )* \) /x;This matches arbitrarily nested parentheses and can replace our earlier $Tiefe0:
if ($text =~ m/\b( \w+$Tiefe_N )/x) {
print "Funktionsaufruf gefunden: $1\n";
}Ha! It takes some mental effort, but once it clicks, applications appear everywhere.
With the basic technique established, let us refine it. Capturing parentheses can become noncapturing, or better, atomic: we capture nothing, and backtracking does not matter either. Atomic groups also let us replace ˹[^()]˼ with ˹[^()]+˼; otherwise, competing quantifiers would cause interminable matching (see Back to reality).
Finally, move ˹\(˼ and ˹\)˼ to surround the dynamic construct, invoking it only when nested parentheses actually occur. The improved version is:
$Tiefe_N = qr/ (?> [^()]+ | \( (??{ $Tiefe_N }) \) )* /x;The outer parentheses ˹\(...\)˼ are gone, so they must be supplied explicitly when using $Tiefe_N. Now the regex also works where parentheses might occur, not only where they exist.
if ($text =~ m/\b( \w+ \( $Tiefe_N \) )/x) {
print "Funktionsaufruf gefunden: $1\n";
}if (not $text =~ m/^ $Tiefe_N $/x) {
print "Öffnende und schließende Klammern stimmen nicht überein!\n";
}We will use this $Tiefe_N regex in a program under Emulating possessive quantifiers in Perl.
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