XML technologies / Regular expressions / Perl / Unusual techniques with Perl regex extensions / Overloading regex literals

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

With overloading , the elements of a regex literal can be preprocessed in any imaginable way. The next sections present examples.

 

Adding start-of-word and end-of-word metacharacters

In Perl there are no dedicated start-of-word and end-of-word metacharacters such as ˹\<˼ and ˹\>˼, since ˹\b˼ usually suffices. If needed, however, we can overload the metacharacters ›\<‹ and ›\>‹ and substitute the constructs ˹(?<!\w)(?=\w)˼ and ˹(?<=\w)(?!\w)˼.

First, write a subroutine RegexLiteralVerarbeiten to perform this replacement:

sub RegexLiteralVerarbeiten($)
{
   my ($RegexLiteral) = @_; # Argument ist ein String.
   $RegexLiteral =~ s/\\</(?<!\\w)(?=\\w)/g; # \< für Wortanfang imitieren.
   $RegexLiteral =~ s/\\>/(?<=\\w)(?!\\w)/g; # \> für Wortende imitieren.
   return $RegexLiteral; # Möglicherweise veränderten String zurückgeben.
}

Passing a string such as ›...\<...‹ to this function converts it to ›...(?<!\w)(?=\w)...‹. Remember that a substitution’s replacement text is treated as a double-quoted string, so write ›\\w‹ to obtain the value ›\w‹.

To apply this replacement to every regex literal, put the routine in a file named MyRegexStuff.pm and use the overloading mechanism:

package MyRegexStuff; # Eindeutiger Name.
use strict;           # Gute Gewohnheit.
use warnings;         # Gute Gewohnheit.
use overload;         # Wir benutzen den Overload-Mechanismus.
# Unsere Regex-Verarbeitung wird installiert, wenn das Modul mit ›use‹ geladen wird.
sub import { overload::constant qr => \&RegexLiteralVerarbeiten }

sub RegexLiteralVerarbeiten($)
{
   my ($RegexLiteral) = @_;  # Argument ist ein String.
   $RegexLiteral =~ s/\\</(?<!\\w)(?=\\w)/g;  # \< für Wortanfang imitieren.
   $RegexLiteral =~ s/\\>/(?<=\\w)(?!\\w)/g;  # \> für Wortende imitieren.
   return $RegexLiteral;     # Möglicherweise veränderten String zurückgeben.
}

1; # Standardformulierung: Ein Package muss ›wahr‹ zurückgeben.

If MyRegexStuff.pm is installed on the library search path (PERLLIB; see Perl’s documentation), the module can be used in Perl scripts. For testing, leave it in the current directory alongside this test script:

use lib '.';          # Sicherstellen, dass Module im aktuellen Verzeichnis gesucht werden.
use MyRegexStuff;     # Jetzt können wir Wortanfang und -ende benutzen!
  ...
$text =~ s/\s+\</ /g; # Whitespace vor einem Wort in ein einzelnes Leerzeichen verwandeln.
  ...

To use the new metacharacters in regex literals, load the module with use MyRegexStuff. Naturally, the new metacharacters are unavailable within MyRegexStuff.pm itself, because within the module MyRegexStuff it is best to avoid the directive use MyRegexStuff .

 

Emulating possessive quantifiers in Perl

Let us extend MyRegexStuff.pm to support possessive quantifiers such as ˹x++˼ (see Possessive quantifiers). Possessive quantifiers initially behave like ordinary greedy quantifiers, but never give back characters they have consumed. Atomic groups can emulate this: remove the final ›+‹ and enclose the result in atomic parentheses, transforming ˹Regex*+˼ into ˹(?>Regex*)˼ (see Possessive quantifiers: ?+, *+, ++ and {m,n}+).

The Regex part may be a parenthesized subexpression, a metasequence such as ˹\w˼ or ˹\x{1234}˼, or a simple character. Handling every case correctly is not easy, so for now we will focus on ?+, *+˼ or ++˼ quantifying a parenthesized subexpression. Using the regex $Tiefe_N from Matching nested pairs with dynamic regular expressions, this also works with nested parentheses. Add this line to our RegexLiteralVerarbeiten function:

$RegexLiteral =~ s/(  \( $Tiefe_N \)[*+?]  )\+/(?>$1)/gx;

That is all. With our new MyRegexStuff module, we can use possessive quantifiers in regex literals, as in this example from Allowing escaped quotes in quoted strings:

$text =~ s/"(\\.|[^"])*+"//; # Strings in Anführungszeichen entfernen.

Supporting every other construct besides parenthesized subexpressions is not easy. Many kinds of regex elements can be followed by a quantifier. Here is one possible approach:

$RegexLiteral =~ s{
 (
   # Finde etwas, das quantifiziert sein kann ...
   (?:  \\[\\abCdDefnrsStwWX] # \n, \w usw.
     |  \\c.                  # \cA
     |  \\x[\da-fA-F]{1,2}    # \xFF
     |  \\x\{[\da-fA-F]*\}    # \x{1234}
     |  \\[pP]\{[^{}]+\}      # \p{Letter}
     |  \[\]?[^]]+\]          # Zeichenklasse
     |  \\\W                  # \*
     |  \( $Tiefe_N \)        # (...), beliebig verschachtelt
     |  [^()*+?\\]            # Fast alles andere
    )
    # ... und auf das tatsächlich ein Quantor folgt ...
    (?: [*+?] | \{\d+(?:,\d*)?\} )
 )
 \+  # ... mit einem zusätzlichen possessiven ›+‹ nach dem Quantor.
}{(?>$1)}gx;

The regex follows the simpler version’s design: find an item followed by a possessive quantifier, remove the plus sign, and wrap it in ˹(?>...)˼. Again, this does not handle all the complexities of Perl syntax. In particular, the character-class branch mishandles escaped characters. Worse, the entire approach is flawed, since these substitutions do not cover every subtlety of regular expressions. For an expression such as ›\(blah\)++‹, for example, the backslashes are ignored and the code assumes the quantifier ˹++˼ applies to more than just the ˹\)˼.

Handling these problems correctly requires considerable effort. One could scan the entire regex from start to finish, as in the HTML example in the box An example of using \G in Perl. I would settle for fixing the character-class part; the rest is hardly worthwhile. The other failing cases are subtle enough that proper character-class handling would make the solution useful in practice. Above all, Perl’s current overloading mechanism has a serious bug that makes the entire effort rather pointless.

  

 

 

 

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