XML technologies / Regular expressions / Features and dialects / Common metacharacters / Grouping and capturing parentheses, logical and greedy constructs

 

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

 

Grouping and capturing parentheses: (...), \1, \2, ...

Plain parentheses generally serve two purposes: grouping and saving matched text. Most dialects use the notation ˹(...)˼, occasionally ˹\(...\)˼, as in GNU Emacs, sed, vi and grep.

Groups are numbered left to right by their opening parentheses, as shown in the figures Capturing text with parentheses, Nested parentheses and Nested parentheses, $1 and $2. Where backreferences are supported, later in the regex use ˹\1˼, ˹\2˼ to match text captured by the corresponding group.

Parentheses often extract substrings and other data from strings. Text matched by the enclosed subexpression, called captured text, remains available after matching. Access differs by language; in Perl, the variables $1, $2, and so on, are used. A common mistake is using the ˹\1˼ syntax outside the regex; that syntax belongs to sed and vi. The table shows how various programs expose captured text for subsequent use.

 

Table: accessing captured text in various programs.

Program

Entire match

First capturing group

GNU egrep

-

-

GNU Emacs

(match-string 0)
(\& in replacement text)

(match-string 1)
(\1 in replacement text)

GNU awk

substr($text, RSTART, RLENGTH)
(\& in replacement text)

-

MySQL

-

-

Perl
(see Side effects of successful matching)

$&

$1

PHP
(see Accessing match data)

$treffer[0]

$treffer[1]

Python
(see Regular expressions in Python)

MatchObj.group(0)

MatchObj.group(1)

Ruby

$&

$1

GNU sed

\& (only in replacement text for s///)

\1 (only in regexes and replacement text)

Java
(see Using regular expressions in Java)

MatcherObj.group()

MatcherObj.group(1)

Tcl

In variables supplied by the caller to regexp or regsub.

VB.NET
(see Regular expressions in VB and other .NET languages)

MatchObj.Groups(0)

MatchObj.Groups(1)

C#

MatchObj.Groups(0)

MatchObj.Groups(1)

vi

&

\1

For program versions, see: Program versions in this book.

 

Grouping-only, noncapturing parentheses: (?:...)

With grouping-only or noncapturing parentheses, ˹(?:...)˼, text matched inside is not saved. They serve only to group alternation or quantifiers and are not counted when numbering for $1, $2, and so on. For example, after a successful match with ˹(1|ein)(?:und|oder)(2|zwei)˼, the variable $1 contains ›1‹ or ›ein‹, and $2 contains ›2‹ or ›zwei‹.

Noncapturing parentheses are useful in several ways. They clarify complex regexes: readers need not wonder whether captured text is referenced elsewhere using $1. They also save time and memory by avoiding capture. Efficiency is discussed in The art of writing regular expressions.

They are handy when assembling a large regex from components. In the example in A regex collection, the variable $HostnameRegex contains a regex. Suppose we want the whitespace before and after a hostname, using m/(\s*)$HostnameRegex(\s*)/. After matching, $1 contains the preceding whitespace and $2 the following whitespace—or so one might think! Wrong: trailing whitespace goes into $4, because $HostnameRegex already contains two capturing groups:

$HostnameRegex = qr/[-a-z0-9]+(\.[-a-z0-9]+)*\.(com|edu|info)/i;

Using noncapturing parentheses in $HostnameRegex instead would avoid the unpleasant surprise:

$HostnameRegex = qr/[-a-z0-9]+(?:\.[-a-z0-9]+)*\.(?:com|edu|info)/i;

Another solution, unavailable in Perl, gives parentheses names instead of numbers.

 

Named subexpressions: (?<Name>...)

Python, PHP’s preg functions, and .NET allow naming a capturing subexpression. Python and PHP use ˹(?P<Name>...)˼, while .NET uses ˹(?<Name>...)˼, which I prefer. A .NET example:

˹\b(?<Land>\d+)-(?<Vorwahl>\d+)-(?<Num>\d+)\b˼

And its Python/PHP equivalent:

˹\b(?P<Land>\d+)-(?P<Vorwahl>\d+)-(?P<Num>\d+)\b˼

The names receive the corresponding phone-number digits. Programs access the substrings by name, for example with RegexObj.Groups("Land") in VB.NET and most .NET languages, RegexObj.Groups["Land"] in C#, RegexObj.group("Land") in Python, and $treffer["Land"] in PHP.

Within the regex, named captures can also be accessed as backreferences: in .NET with ˹\k<Land>˼, and in Python and PHP with ˹(?P=Land)˼.

Python and .NET, unlike PHP, allow repeating a name within one regex. A phone area code is often parenthesized, as in (nnn). For this, .NET syntax allows ˹...(?:\((?<Vorwahl>\d+)\)|(?<Vorwahl>\d+))...˼. In either case, the area code is captured by the named expression Vorwahl .

 

Atomic parentheses: (?>...)

Atomic parentheses, ˹(?>...)˼, become easy to understand once you know how the regex engine works in detail (see ...)">Atomic groups with (?>...)). A brief example must suffice here. Once the subexpression matches, it never relinquishes its text before the entire search ends: it becomes an indivisible “atom”, unless the entire atomic group is abandoned or reapplied.

The regex ˹¡.*!˼ normally matches ›¡Hola!‹, but it no longer matches if ˹.*˼ is enclosed in atomic parentheses, ˹¡(?>.*)!˼. In both cases, ˹.*˼ first matches as many characters as possible, ›¡Hola!‹. In the first case, however, ˹.*˼ is forced by the final ˹!˼ to relinquish one character, ›!‹, allowing the entire regex to match. In the second case, ˹.*˼ is inside atomic parentheses, which never give characters back, leaving nothing for the final ˹!˼, so no match is found.

This shows how atomic groups work, but not why they are useful. They can greatly speed matching (see Faster failures with atomic groups) and give finer control over which regex parts should match (see Avoiding eternal matching with atomic parentheses).

 

Alternation: ... |... | ...

Alternation allows one of several subexpressions at a position. Those subexpressions are called alternatives. The symbol ˹|˼, a vertical line, has several names, including “or” and bar. Some dialects instead use ˹\|˼.

Alternation has very low precedence, so ˹dies und|oder das˼ means the same as ˹(dies und)|(oder das)˼ rather than ˹dies (und|oder) das˼, although the latter was probably intended.

Most dialects allow the empty alternative ˹(klipp|klar|)˼ . It always matches, so the example is logically comparable to ˹(klipp|klar)?˼. More precisely, ˹(klipp|klar|)˼ is equivalent to ˹((?:klipp|klar)?)˼. The difference from ˹(klipp|klar)?˼ is slight, but some languages distinguish an empty capture from a group that did not participate. The POSIX standard forbids empty alternatives, as do lex and most versions of awk. I find them useful for clarity. Larry Wall once explained: “It is just like zero in the number system.”

 

Conditional regexes: (? if then | else)

This construct expresses an if/then/else condition inside a regex. The if part contains a special logical condition, discussed shortly. The parts after then and else are ordinary subexpressions. If the condition in if is true, the then subexpression applies; otherwise, the engine tries the else subexpression. The else part is optional; without it, the preceding ›|‹ may also be omitted.

What can be tested in if depends on the dialect. Usually this is an earlier capture or a lookaround construct.

Testing capturing groups

A parenthesized number in if tests whether that capturing group has participated so far. Here is an HTML example with a <IMG> tag, either alone or within <A>...</A> tags. We use free-spacing mode; the condition, without an else part, is (?(1)...):

( <A\s+[^>]+> \s* )?  # <A>-Tag, falls vorhanden.
<IMG\s+[^>]+>         # <IMG>-Tag.
(?(1)\s*</A>)         # </A>-Tag, falls wir vorhin ein <A> gefunden hatten.

The (1) in ˹(?(1)...)˼ tests whether the first group participated. “Participated” does not mean the same as “matched one or more subject characters”.

Consider two approaches to matching a word optionally enclosed in angle brackets: ˹(<)?\w+(?(1)>)˼ works, but ˹(<?)\w+(?(1)>)˼ does not. Only the first question mark’s position differs. In the correct first approach, it makes the whole group optional. In the second, the group is mandatory; only its ˹<˼ is optional. The group therefore always participates, whether or not ›<‹ was found, making the condition in if always true.

With named groups (see Named subexpressions), their names may replace group numbers.

Testing lookaround

The if part may contain a complete lookaround, such as ˹(?=...)˼ or ˹(?<=...)˼. If it succeeds, the condition is true and then applies; otherwise, else is used. A somewhat contrived example: ˹(?(?<=NUM:)\d+|\w+)˼ searches, after a ˹NUM:˼, for digits (˹\d+˼), or otherwise a word (˹\w+˼). The lookbehind is underlined.

Other condition tests

Perl extends this construct to allow arbitrary Perl code in if. The code runs, its return value is tested, and the corresponding then or else subexpression applies. Details appear in Crazy things with Perl regex extensions under Perl.

 

Greedy quantifiers: *, +, ?, {min, max}

Quantifiers—star, plus, question mark, and intervals, metacharacters describing the quantity of preceding elements—have already been covered. Note that some programs use ˹\+˼ and ˹\?˼ instead of ˹+˼ and ˹?˼. Some prohibit quantifying backreferences, others parenthesized expressions.

Intervals: {min, max} or \{min, max\}

Intervals are counting quantifiers, specifying minimum and maximum occurrences. With one number, as in ˹[a-z]{3}˼ or ˹[a-z]\{3\}˼, depending on dialect, exactly that number must occur. This equals ˹[a-z][a-z][a-z]˼, which some engines handle more efficiently (see Small quantifiers).

A warning: do not use something like ˹X{0,0}˼ to mean “No X may appear here.” ˹X{0,0}˼ is meaningless, roughly “No requirement for an X here; instead, match nothing at all.” This is equivalent to omitting ˹X{0,0}˼ altogether. If an X occurs, later regex elements can still match it, defeating the intention. This description of {0,0} is theoretically correct, but practice is worse, almost random. Many tools, including GNU awk, GNU grep , and old Perl versions, apparently treat {0,0} like *. Others, most sed versions and some grep versions, treat it like ?. Crazy! To require “No X here”, use negative lookahead instead.

 

Lazy, nongreedy quantifiers: *?, +?, ??, {min, max}?

Several tools provide the awkward-looking quantifiers *?, +?, ?? or {min, max}?. These are the nongreedy (non-greedy or lazy) versions of the familiar quantifiers. Ordinary quantifiers are greedy, matching as much text as possible. Lazy ones consume as little as possible while still allowing the whole regex to match. This far-reaching difference is discussed in How regex engines work (see Two important backtracking rules).

 

Possessive quantifiers: *+, ++, ?+, {min, max}+

Currently, possessive quantifiers are supported only by java.util.regex and PCRE, hence PHP, though they may appear elsewhere. Like greedy quantifiers, possessive ones match as many characters as possible, but never give any back once taken. Like their relatives, atomic parentheses, they are easier to understand once the matching internals are understood, the subject of How regex engines work.

In a sense, possessive quantifiers are shorthand, since atomic groups can replace them. The result of ˹.++˼ is identical to ˹(?>.+)˼, though a good implementation might optimize the possessive form better (see Discarding unnecessary saved states with possessive quantifiers).

  

 

 

 

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