XML technologies / Regular expressions / Features and dialects / Common metacharacters / Anchors and other zero-width assertions
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
Line anchors and some other metacharacters are zero-width assertions: they match no characters, but instead match a particular position in the text.
Start of line, start of string: ^, \A
The circum⟦U+0003⟧flex ˹^˼ matches the start of the text being searched and, in multiline mode (see Enhanced line-anchor mode, or multiline mode), the positions after every newline in the text. In some systems, ˹^˼ in multiline mode also matches the position after a Unicode line-ending character (see Line endings in Unicode).
The anchor ˹\A˼, when supported, always matches only the start of the subject text, regardless of mode.
End of line, end of string: $, \Z, \z
As the next table suggests, the notion of an end of line is somewhat more complicated than its counterpart. Depending on the tool used, ˹$˼ has a slightly different effect. Usually it matches the end of the string, but also the position before a newline at the end of the subject text. Thus, ˹s$˼ loosely means “an s at the end of a line,” whether or not the line has a line-ending character (›...sNL‹) or not.
There are two other possible meanings: in some systems, ˹$˼ matches only the exact end of the subject text; in others, the position before a newline. Some Unicode-aware systems recognize the position after every Unicode line-ending character (see Line endings in Unicode; in Java the meaning of ˹$˼ with respect to Unicode line-ending characters is very confusing; see Unicode line-ending characters).
Depending on the regex mode (see Enhanced line-anchor mode, or multiline mode), the effect of ˹$˼ changes to also recognize the position before every newline (or Unicode line-ending character) within the string.
When the metacharacter ˹\Z˼ is supported, it recognizes the same thing as ˹$˼ in normal mode (not multiline mode). In most implementations, this is the position at the end of the subject text and before a newline at its end. The anchor ˹\z˼ matches only the exact end of the subject text, regardless of modes and newlines.
Table: String and line anchors in some scripting languages.
Property |
| Java | Ruby | Tcl | .Net | ||||
|---|---|---|---|---|---|---|---|---|---|
Normally... | |||||||||
| matches | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | |
| matches | ✓2 | |||||||
| matches | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | |
| matches | ✓1 | ✓ | ✓ | ✓ | ✓ | ✓ | ||
| matches | ✓2 | |||||||
| |||||||||
Enhanced line-anchor mode is supported (see | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | |||
In enhanced line-anchor mode (multiline mode)... | |||||||||
| matches | ✓ | ✓ | ✓ | ✓ | - | ✓ | ✓ | |
| matches | ✓1 | ✓ | ✓ | ✓ | - | ✓ | ✓ | |
| matches | ✓ | ✓ | ✓ | ✓ | - | ✓ | ✓ | |
| matches | ✓1 | ✓ | ✓ | ✓ | - | ✓ | ✓ | |
| |||||||||
| ✓ | ✓ | ✓ | ✓ | ●4 | ✓ | ✓ | ||
| ✓ | ✓ | ✓ | ●3 | ●5 | ✓ | ✓ | ||
| ✓ | ✓ | ✓ | - | - | ✓ | ✓ | ||
| |||||||||
✓1 | Sun’s Java regex package supports Unicode line-ending characters in these cases. | ||||||||
✓2 | In Ruby, |
| |||||||
●3 | In Python, |
| |||||||
●4 | In Ruby, |
| |||||||
●5 | In Ruby, |
| |||||||
For program versions, see: Program versions used in this book. | |||||||||
Start of the next match (or end of the previous match): \G
The metacharacter ˹\G˼ was first introduced in Perl in connection with global matching using /g (see Example program: Mail merge). It matches the position where the previous match ended. On the first iteration, this is the start of the string, as with ˹\A˼.
If no match is found, the position matched by ˹\G˼ is reset to the start of the subject string. When a regular expression is applied repeatedly, for example with ˹s/.../.../g˼ in Perl or a “Match all” function in another language, the final iteration finds no match, resetting the position for ˹\G˼ to the start of the subject string.
The ˹\G˼ has three special aspects that I find useful and interesting:
The position associated with
˹\G˼is a property of the subject string, not of any regex in which˹\G˼occurs. This means that several different regular expressions can search the same string, with˹\G˼continuing where the previous search stopped.Perl also has the modifier
/c(see Matching each text element individually with /gc), which causes the˹\G˼position after an unsuccessful search not to be reset to the start of the subject string. This allows a string to be tested with different regular expressions, moving forward only when a regex matches.The position in the subject string associated with
˹\G˼can be queried and modified outside the regex (using Perl’sposfunction). It could thus be initialized before any matching takes place. If the language supports this facility, it can also simulate the behavior described above (with/c) when it is not implemented.
In An example of using \G in Perl you will find a worked example of a useful application that would require much more complicated code without ˹\G˼. Unfortunately, in Perl, ˹\G˼ works reliably only at the very start of the regex; fortunately, that is where it probably belongs in the vast majority of cases anyway.
End of the previous match or start of the current attempt?
Depending on the implementation, ˹\G˼ refers to the start of the current match attempt or the end of the previous match. Usually these coincide, so this subtle distinction does not matter. But there is a difference, and Processing CSV files shows a practical example where it does matter. A contrived example makes the difference easier to understand. Suppose ˹x?˼ is applied to the string ›abcde‹. The regex matches at ›▵abcde‹, consuming no text. A global search applies the regex repeatedly until no match is found, always starting where the previous match ended—unless the transmission of the regex engine intervenes. Here there would be an infinite loop if every iteration searched the same position, so the transmission advances one character when it detects this situation (see The transmission advances to the next character). You can clearly see this behavior with s/x?/!/g: you get ›!a!b!c!d!e!‹.
As a side effect, the end of the previous match and the start of the current attempt no longer coincide. This immediately raises the question: which of these positions does ˹\G˼ match? In Perl, s/\Gx?/!/g yields ›!abcde‹, so in Perl, ˹\G˼ refers to the end of the previous match. When the transmission advances one character after the first round, ˹\G˼ no longer matches, and matching stops.
In other languages it is the other way round: without ˹\G˼ you get ›!a!b!c!d!e!‹; thus, ˹\G˼ there refers to the start of the next attempt, after the regex transmission has advanced one character.
Even the documentation cannot be trusted here: both Microsoft’s .NET documentation and Sun’s Java package documentation were unreliable on this point until I pointed out the errors. Thus, ˹\G˼ refers to the start of the current attempt in PHP and Ruby, but to the end of the previous match in Perl, java.util.regex and the .NET languages.
An example of using \G in Perl |
Here is a sketch of a small program that checks HTML code in the variable The code relies on the behavior of the match operator With this behavior, the various regular expressions ( |
my $need_close_anchor = 0; # ›Wahr‹, wenn wir ein <A>, aber noch kein schließendes
# </A> angetroffen haben.
while (not $html =~ m/\G\z/gc) { # Solange wir noch nicht alles durchgearbeitet haben ...
if ($html =~ m/\G(\w+)/gc) {
# Wir haben ein Wort oder eine Zahl in $1, die wir jetzt prüfen könnten ...
} elsif ($html =~ m/\G[^<>&\w]+/gc) {
# Weder Wort noch Zahl noch HTML -- erlaubt.
} elsif ($html =~ m/\G<img\s+([^>]+)>/gci) {
# Image-Tag, Inhalt auf Zulässigkeit prüfen ...
.
.
.
} elsif (not $need_close_anchor and $html =~ m/\G<A\s+([^>]+)>/gci) {
# Ein Link -- den wir hier überprüfen können ...
.
.
.
$need_close_anchor = 1; # Wir brauchen jetzt ein </A>.
} elsif ($need_close_anchor and $html =~ m{\G</A>}gci){
$need_close_anchor = 0; # </A> gefunden, kein weiteres erlaubt.
} elsif ($html =~ m/\G&(#\d+|\w+);/gc) {
# Entities wie > oder { zulassen.
} else {
# Bis hier nichts erkannt, muss ein Fehler sein. Wir holen ein Dutzend Zeichen aus dem
# HTML-Text ab der aktuellen Position und geben damit eine Fehlermeldung aus.
my $location = pos($html); # \G-Position ist der Offset des Fehlers.
my ($badstuff) = $html =~ m/\G(.{1,12})/s;
die "Unerwartetes HTML bei $location: $badstuff\n";
}
}
if ($need_close_anchor) { # Sicherstellen, dass kein offenes <A> zurückbleibt.
die "Kein </A> am Ende."
}Word boundaries: \b, \B, \<, \>, ...
Like line anchors, word-boundary metacharacters match a particular position in the subject string. There are two approaches: one uses two different metasequences for the start of a word and end of a word (usually \< and \>); the other uses a single metasequence for a word boundary (usually \b). Both variants usually provide another metasequence for a non-word boundary (usually \B). The next table lists these metasequences for several tools and languages. If a tool lacks explicit start-of-word and end-of-word metacharacters but supports lookaround, lookaround constructs can emulate the word-boundary condition. Where possible, I have included these substitutes in the table.
A word boundary is usually defined as a position with a word character on one side and a non-word character on the other. Exactly which characters count as word characters depends on the tool. It would certainly make sense for this definition to agree with that of \w, but that is not always the case.
Table: Some tools and their word-boundary metasequences.
Program | Start of word ... end of word | Word boundary | Non-word boundary |
|---|---|---|---|
GNU awk |
|
|
|
GNU egrep |
|
|
|
GNU Emacs |
|
|
|
Java |
|
|
|
MySQL |
|
| |
.NET |
|
|
|
Perl |
|
|
|
PHP |
|
|
|
Python |
|
|
|
Ruby |
|
| |
GNU sed |
|
|
|
Tcl |
|
|
|
For program versions, see: Program versions used in this book. | |||
In PHP and java.util.regex, for example, \w refers only to ASCII, not all Unicode characters, so in the lookaround substitutes in the table I replaced \w with the Unicode Letter property \pL (which is itself shorthand for ˹\p{L}˼; see Unicode properties, scripts, and blocks).
Whatever counts as a word character, these word anchors simply compare two adjacent characters. No regex implementation consults a dictionary or performs linguistic analysis to decide what is a word: all systems consider “NE14AD8” a word, but not “M.I.T.”.
Lookahead: (?=...), (?!...); lookbehind: (?<=...), (?<!...)
Lookahead and lookbehind constructs (collectively called lookaround ) were already discussed in depth in Grouping large numbers into threes: Lookaround using an extended example. We left out one important issue: the kinds of expressions permitted in each lookbehind construct. Most implementations limit the length of the text a lookbehind may match; lookahead has no such restrictions.
Perl and Python impose the strictest restriction: the lookbehind parentheses may match only a fixed-length string. For example, (?<!\w) and (?<!klipp|klar) are allowed, but not (?<!Flops?) and (?<!^\w+:), since those can match text of different lengths. Sometimes the expression can be rewritten, for example replacing (?<!Flops?) with ˹(?<!Flop)(?<!Flop|Flops)˼, but that is not particularly clear.
The next level of implementations allows alternatives of different lengths within lookbehind, so (?<!Flops?) can then be replaced with (?<Flop|Flops). PCRE, and thus PHP’s preg functions, support this.
Things become easier still when lookbehind can match text of varying length up to a fixed maximum. This directly permits (?<!Flops?), but not (?<!^\w+:), since its matched string can be arbitrarily long. This is how the regex implementation in Sun’s Java package behaves.
In principle, these three restricted forms of lookbehind are equivalent, since all three can be simulated using the simplest form, although this can be very cumbersome. The fourth and most comprehensive implementation allows lookbehind expressions that match strings of any length; even (?<!^\w+) is allowed. Microsoft’s .NET languages support this kind of lookbehind. Careless use can, however, produce very inefficient code. A lookbehind that can match strings of any length requires the regex engine to go back to the start of the string and test every possible match; when the current position is at the end of a long string, this becomes enormously expensive.
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