XML technologies / Regular expressions / Perl / Unusual techniques with Perl regex extensions / Emulating named subexpressions
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
Despite the shortcomings of overloading regex literals, I would like to present a larger example combining several special constructs of Perl. Perl cannot assign names to parenthesized subexpressions (see Named subexpressions), but capturing groups and $^N can emulate this feature. The variable $^N contains the text from the capturing group most recently closed (see $^N). (I specifically, and apparently successfully, posed as a Perl developer and introduced $^N so that named groups could be emulated in Perl.)
First consider a simple example:
˹href\s*=\s*($HttpUrl)(?{ $url = $^N })˼
This uses the regex object $HttpUrl from Building and using regex objects. The underlined part is a code pattern that saves the text matched by $HttpUrl in the variable $url . In this simple case, instead of $^N we could simply use $1 and omit the code pattern entirely, since we could just as well use $1 after matching. But suppose this simple regex is stored as an object and reused several times within a larger regex:
my $UrlSpeichern = qr{
($HttpUrl) # Eine HTTP-URL finden ...
(?{ $url = $^N }) # ... und in $url abspeichern.
}x;
$text =~ m{
http \s*=\s* ($UrlSpeichern)
| src \s*=\s* ($UrlSpeichern)
}xi;Whichever alternative matches, the URL found is always saved in $url. Other techniques would work here too, for example using the variable $+, but if $UrlSpeichern is used in more complex situations, those approaches become confusing and difficult to maintain. Named groups are indeed very useful here.
Emulating named subexpressions
package MyRegexStuff;
use strict;
use warnings;
use overload;
sub import { overload::constant('qr' => \&RegexLiteralVerarbeiten) }
my $VerschachtelRegex; # »Forward«-Deklaration, Regex wird rekursiv verwendet.
$VerschachtelRegex = qr{
(?>
(?: # Weder Klammern noch # noch ein Escape …
[^()\#\\]+
# Maskierte Zeichen …
| (?s: \\. )
# Kommentar in der Regex …
| \#.*\n
# Klammerpaar mit verschachtelten Klammern …
| \( (??{ $VerschachtelRegex }) \)
)*
)
}x;
sub RegexUmbauen($); # »Forward«-Deklaration, wird rekursiv verwendet.
sub RegexUmbauen($)
{
my $re = shift; # Die umzubauende Regex.
$re =~ s{
\(\? # "(?"
< ( (?>\w+) ) > # < $1 > $1 ist ein Bezeichner.
( $VerschachtelRegex ) # $2 - möglicherweise verschachtelte Dinge.
\) # ")"
}{
my $id = $1;
my $Innerei = RegexUmbauen($2);
# Wir ersetzen
# (?<id>Innerei)
# durch
# (?: (Innerei) # Passt auf die »Innerei«.
# (?{
# local($^N{$id}) = $Innerei # Lokalisiertes Element von %^T.
# })
# )
"(?:($Innerei)(?{ local(\$^T{'$id'}) = \$^N }))"
}xeog;
return $re; # Umgebaute Regex zurückgeben.
}
sub RegexLiteralVerarbeiten($)
{
my ($RegexLiteral) = @_; # Argument ist ein String.
# print "VORHER: $RegexLiteral\n"; # Zum Debuggen auskommentieren.
my $neu = RegexUmbauen($RegexLiteral);
if ($neu ne $RegexLiteral)
{
my $vorher = q/(?{ local(%^T) = () })/; # Temporären Hash lokalisieren.
my $nachher = q/(?{ %^N = %^T })/; # In »wirklichen« Hash umkopieren.
$RegexLiteral = "$vorher(?:$neu)$nachher";
}
# print "NACHHER: $RegexLiteral\n"; # Zum Debuggen auskommentieren.
return $RegexLiteral;
}
1;One problem with the current version is that the variable $url is not restored during Backtracking. As in local in a code pattern, we therefore need a temporary local variable and copy its value into a normal variable after a successful match.
The program in the box above, Emulating named subexpressions, shows one way to implement named groups. The user writes a regex such as ˹(?<Num>\d+)˼ and, on success, receives the number matched by ˹\d+˼ in a global hash named %^N, specifically in the hash element $^N{Num}. Future Perl versions might make %^N a special variable, but in the current version it is an ordinary variable, which is why I chose it.
I could have chosen a name such as %NamedCapture, but %^N has two advantages. First, it resembles the variable $^N; second, even under use strict this hash need not be declared with our. I also hope Perl will eventually support named groups natively, and I think %^N would be the right approach. In that case, %^N would probably get its own dynamic scope like the other match variables ($1, @+ and so on; see Special variables controlled by matching). In this solution, it is an ordinary global variable with no automatic dynamic scoping.
This approach also suffers from the problems common to all programs using regex overloading: interpolated variables interfere with overloading.
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