XML technologies / Regular expressions / Perl / Unusual techniques with Perl regex extensions / Perl code in the regex

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

Code patterns are especially useful for debugging and collecting information during matching. The examples lead to a method of emulating a POSIX NFA in Perl. As often, the journey matters more than the destination, unless you specifically need POSIX behavior.

Start with simple regex debugging techniques.

 

Code patterns that print during matching

This small program

"abcdefgh" =~ m{
  (?{ print "Regex angesetzt bei [$`|$']\n" })
  (?:d|e|f)
}x;

produces:

Regex angesetzt bei [|abcdefgh]
 Regex angesetzt bei [a|bcdefgh]
 Regex angesetzt bei [ab|cdefgh] 
Regex angesetzt bei [abc|defgh]

The code pattern comes first, so it executes

print "Regex angesetzt bei [$`|$']\n"

whenever the regex starts a new attempt. The output uses $` and $' (see Special variables controlled by matching) (note: I normally discourage the special match variables $`, $& and $' because they can slow the entire program; see The variables $`, $& and $' are “naughty”. Temporary debugging is an exception) to show the subject; ›|‹ marks the current position where the regex starts. The transmission advances three times (see The transmission advances to the next character) before matching at the fourth position.

Adding

(?{ print "Regex passt bei [$`<$&>$']\n" })

at the end would print this after the four lines:

Regex passt bei [abc<d>efgh]

Compare this program, where only the regex's main body ˹(?:d|e|f)˼ is replaced by ˹[def]˼:

"abcdefgh" =~ m{
  (?{  print "Regex angesetzt bei [$`|$']\n" })
  [def]
}x;

Results should be identical, but instead we get only:

Regex angesetzt bei [abc|defgh]

Why? In the second case, Perl can apply first-character optimization to ˹[def]˼ (see First-character optimization). The transmission skips positions guaranteed to fail, here all but the final successful one. The code pattern reveals what happens during matching.

 

panic: top_env

If code patterns or dynamic constructs abruptly terminate your program with

panic: top_env

, a syntax error in one of those constructs is likely. This Perl version handles some syntax errors poorly and gives up. Fix the error.

 

Using code patterns to print all possible matches

Perl's traditional NFA stops at the first match, even if others exist. Clever code patterns can make Perl print all possible matches. Revisit the ›motorrad‹ example from Really the longest match:

"motorradfahren" =~ m{
    motor(rad)?(radfahren)?
   (?{ print "Treffer bei [$`<$&>$']\n" })
}x;

This prints the expected

Treffer bei [<motorrad>fahren]

, matching the underlined part of ›motorradfahren‹.

However, the text “Treffer bei” describes not necessarily the final match, but the match at that point in the search. Here they coincide, because the code pattern is last. When the regex engine reaches it, all text has been matched, so it prints the final result.

What happens if we append ˹(?!)˼ after the code pattern? ˹(?!)˼ is a negative lookahead that always fails locally. The failure occurs just after the code pattern prints its match line and forces the engine to use backtracking to seek another match. Failure occurs after each printed match, exploring all paths and printing all possible matches:

Treffer bei [<motorrad>fahren]
 Treffer bei [<motorradfahren>]
 Treffer bei [<motor>radfahren] 

By forcing every otherwise successful match to fail, we make the engine find and print them all. Without ˹(?!)˼, Perl returns the first match; with ˹(?!)˼, other possibilities print too.

What do you think this snippet prints?

"123" =~ m{
   \d+
   (?{ print "Treffer bei [$`<$&>$']\n" })
   (?!)
}x;

It prints:

Treffer bei [<123>]
 Treffer bei [<12>3]
 Treffer bei [<1>23]
 Treffer bei [1<23>]
 Treffer bei [1<2>3]
 Treffer bei [12<3>] 

The first three lines are expected; the next three require closer attention. (?!) forces backtracking, producing lines two and three. Once the first start position fails, the transmission advances one character for another attempt, producing lines four and five. The final line comes from the third attempt.

(?!) therefore makes the regex print all possible matches, not merely those from one starting point. Restricting the start can be useful too; we will see how shortly.

 

Finding the longest match

Now find and save the longest match. Store the longest so far and compare each new candidate with it. Our ›motorrad‹ example gives:

$laengster_treffer = undef; # Hier speichern wir den bisher längsten Treffer.

"motorradfahren" =~ m{
   motor(rad)?(radfahren)?
   (?{
      # Überprüfen, ob der aktuelle Treffer ($&) der bisher längste ist.
      if (not defined($laengster_treffer)
          or
          length($&) > length($laengster_treffer))
      {
          $laengster_treffer = $&;
      }
   })
   (?!) # Fehlschlag erzwingen und mit Backtracking andere mögliche »Treffer« finden.
}x;

# Resultat ausgeben, falls ein Treffer gefunden wurde.
if (defined($laengster_treffer)) {
   print "Längster Treffer: [$laengster_treffer]\n";
} else {
   print "Kein Treffer\n";
}

This yields the expected ›Längster Treffer: [motorradfahren]‹. The lengthy code pattern will be reused, so package it with ˹(?!)˼ in its own regex object:

(?{
      # Überprüfen, ob der aktuelle Treffer ($&) der bisher längste ist.
      if (not defined($laengster_treffer)
          or
          length($&) > length($laengster_treffer))
      {
          $laengster_treffer = $&;
      }
   })
   (?!) # Fehlschlag erzwingen und mit Backtracking andere mögliche »Treffer« finden.
}x;

This simple example finds ›9938‹, the absolute longest possible match:

$laengster_treffer = undef; # Hier speichern wir den bisher längsten Treffer.
"800-998-9938" =~ m{  \d+  $LaengstenTrefferSpeichern  }x;

# Resultat ausgeben, falls ein Treffer gefunden wurde.
if (defined($laengster_treffer)) {
   print "Längster Treffer: [$laengster_treffer]\n";
} else {
   print "Kein Treffer\n";
}

 

Finding the leftmost-longest match

We can find the absolute longest match, but now want the longest among those starting furthest left: the POSIX NFA's choice (see The leftmost-longest match). Prevent the transmission from advancing once the first match is found. It may not be longest, but ordinary backtracking explores all matches from that start, retaining the longest.

Perl cannot directly control the transmission. Instead, anchor the regex at the first successful position once the variable $laengster_treffer is defined. Test this with ˹(?{ defined $laengster_treffer })˼, but a test alone is not a regex. The key is the conditional ˹(? if then|else)˼ construct.

Perl code in a conditional regex construct

To make the engine respond to our test, put it in the condition of ˹(? if then|else)˼ (see Conditional regular expressions). We also want it to stop once the variable is defined, so in the then part use the fail-now construct (?!). (The else part is unnecessary and omitted.) Package this conditional in a regex object:

my $BeimErstenTrefferAufgeben = qr/(?(?{ defined $laengster_treffer})(?!))/;

The if part is (?{ defined $laengster_treffer}), and the then part is (?!). Combined with the $LaengstenTrefferSpeichern object, this gives:

"800-998-9938" =~ m{ $BeimErstenTrefferAufgeben \d+ $LaengstenTrefferSpeichern }x;

Thus, ›800‹ is the POSIX match: the longest among those starting furthest left.

  

 

 

 

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