XML technologies / Regular expressions / Perl / The match operator / Iterative matching: scalar context with /g
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
The m/.../g in scalar context differs from the other constructs. Like ordinary m/.../, it finds one match, but like m/.../g in list context, it remembers where the last match ended. Each new application of m/.../g, usually in a loop, finds the next match. After failure, the next attempt starts again at the beginning.
A simple example:
$text = "NAJA! Dies ist ein DUMMER Test.";
$text =~ m/\b([a-z]+\b)/g;
print "Das erste Wort nur aus Kleinbuchstaben: $1\n";
$text =~ m/\b([A-Z]+\b)/g;
print "Das erste darauf folgende GROSSGESCHRIEBENE Wort: $1\n";Both operators run in scalar context using /g. The result:
Das erste Wort nur aus Kleinbuchstaben: ist Das erste darauf folgende GROSSGESCHRIEBENE Wort: DUMMER
The two scalar /g searches cooperate: the first sets the current position after a lowercase word; the second starts there and finds the next uppercase word. Both need /g, first to save the current position, then to resume from it. If /g were absent from just one operator, the second line would find ›NAJA‹.
Scalar /g matching is handy for while loops like this:
while ($KonfigurationsDaten =~ m/^(\w+)=(.*)/mg) {
my($schluessel, $wert) = ($1, $2);
.
.
.
}All matches are found, as in list context, but each success executes one iteration of the while loop. Failure returns false, ending the loop and resetting the current position to the start. The next /g search starts over.
Compare
while ($text =~ m/(\d+)/) { # Achtung!
print "Gefunden: $1\n";
}and
while ($text =~ m/(\d+)/g) {
print "Gefunden: $1\n";
}The tiny difference is /g, but the effect is substantial. If $text contains the earlier IP address, the second version gives:
Gefunden: 64 Gefunden: 156 Gefunden: 215 Gefunden: 240
The first endlessly prints »Gefunden: 64«. Without /g, matching means find the first ˹(\d+)˼ in $text, which is always ›64‹. With /g, it instead means find the next ˹(\d+)˼ in $text, finding all numbers then ending the loop.
Current position and pos()
Each string in Perl has a current position where the transmission starts the regex engine. This belongs to the string, not the regex. Creating or changing a string resets it to the beginning. After successful /g , it stays at the match's end, where the next /g resumes.
The function pos(...) reports a string's current position:
my $ip = "64.156.215.240";
while ($ip =~ m/(\d+)/g) {
printf "Zahl '$1' endet an Position %d\n", pos($ip);
}This prints:
Zahl '64' endet an Position 2 Zahl '156' endet an Position 6 Zahl '215' endet an Position 10 Zahl '240' endet an Position 14
Zero-based position 2 is before the third character. After successful /g, $+[0], the first element of @+ (see @- and @+), equals the value returned by pos().
Without an argument, pos() uses the match operator's default subject, $_.
Setting the current position with pos
More interestingly, pos() is assignable, setting where the next /g search starts. Yahoo! logs I used placed the path after 32 bytes. One way to skip them is ˹^.{32}˼:
if ($Logzeile =~ m/^.{32}(\S+)/) {
$Webseite = $1;
}This makes the engine process all 32 characters. Setting the start explicitly is clearer and faster:
pos($Logzeile) = 32; # Der Pfadname der Webseite beginnt nach dem 32. Zeichen ...
if ($Logzeile =~ m/(\S+)/g) { # ... also mit der Mustersuche dort beginnen.
$Webseite = $1;
}Better, but different: matching starts after 32 characters without requiring preceding text to match as in the first version. If character 32 fails ˹\S˼, the first fails, while the second advances the transmission character by character, perhaps finding a later ˹\S+˼ match, incorrectly. The next section prevents this.
Using ˹\G˼
The metacharacter ˹\G˼ anchors where the previous match ended, exactly what we need:
pos($Logzeile) = 32; # Der Pfadname der Webseite beginnt nach dem 32. Zeichen ...
if ($Logzeile =~ m/\G(\S+)/g) { # ... also mit der Mustersuche dort beginnen.
$Webseite = $1;
}The ˹\G˼ prevents transmission advancement: failure at the current position must fail overall.
The metacharacter ˹\G˼ was introduced under Features and dialects (see Start of the new or end of the previous search: \G) and illustrated under Practical regex techniques (see Staying synchronized with \G).
Note that ˹\G˼ is reliable in Perl only as the first regex element with no top-level alternation. The optimized CSV regex from The art of writing regular expressions (see Unrolling the loop for CSV data) begins with ˹\G(?:^|,)...˼. Since ˹\G˼ is unnecessary when the stricter ˹^˼ matches, one might try ˹(?:^|\G,)...˼. That produces unpredictable results in Perl. (Note: it would work in other dialects supporting ˹\G˼. Still, I advise against this: optimizing an initial ˹\G˼ usually saves more than avoiding occasional checks of ˹\G˼ (see Line- and string-anchor optimizations).)
Matching components individually with /gc
Normally failure of m/.../g resets the subject's position associated with pos to the beginning. The /c modifier prevents this. (/c is always paired with /g, so I often call it /gc.) The m/.../gc construct with ˹\G˼ often implements a lexer or scanner that splits input into components. This example parses HTML in $html:
while (not $html =~ m/\G\z/gc) { # Solange wir noch nicht alles durchgearbeitet haben ... if ($html =~ m/\G( <[^>]+> )/xgc) { print "Tag: $1\n" } elsif ($html =~ m/\G( &\w+; )/xgc) { print "Namen-Entity: $1\n" } elsif ($html =~ m/\G( &\#\d+; )/xgc) { print "Numerisches Entity: $1\n" } elsif ($html =~ m/\G( [^<>&\n]+ )/xgc) { print "Text: $1\n" } elsif ($html =~ m/\G \n /xgc) { print "Newline\n" } elsif ($html =~ m/\G( . )/xgc) { print "Unzulässiges Zeichen: $1\n" } else { die "$0: Ähm: Das kann gar nicht passieren!"; } }
Bold regex parts match specific HTML components. Each is tested from the current position because of /gc, and only at that position because of ˹\G˼.
Try regexes at the same position until one matches and prints. The position given by pos for $html then moves to the next component for the next while iteration.
Stop the loop when m/\G\z/gc matches, meaning current position (˹\G˼) equals string end (˹\z˼).
Every iteration must have a regex that matches. Otherwise, without aborting, the position never advances and the loop is infinite: pos stays unchanged. An else branch safeguards this; currently unreachable, it catches mistakes in extensions. Unexpected sequences such as ›<>‹ produce one warning per character.
Test order also matters, for example placing ˹\G(.)˼ last. To handle blocks of type <script> (sections ), use
$html =~ m/\G ( <script[^>]*>.*?</script> )/xgcsi
. Five modifiers! Place this before generic tags, or the initial ˹<[^>]+>˼ will consume the opening <script> tag.
The box A Perl example using \G under Features and dialects gives a fuller example.
Summary: pos() and related behavior
This table relates matching to the subject's pos:
Matching | Search starts at | pos after success | pos after failure |
|---|---|---|---|
| String start ( | set to | set to |
|
| set to the match's end | set to |
|
| set to the match's end | unchanged |
Any modification of the subject resets pos to undef, the string's beginning.
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