XML technologies / Regular expressions / Perl / Perl-specific regex topics / Special variables controlled by matching

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

Successful matching or substitution sets dynamically scoped, read-only variables (read-only). Failed searches never change them; successful ones always set them, possibly to empty strings or undef, meaning no value. Every success updates all these variables, listed below.

 

Table: special variables after matching.

Special variables set by this search

"Pi ist 3.14159, ungefähr." =~ m/\b(1(2schmackhaft|fettig)2|(3\d+(4\.\d*)4?)3)1\b/;

Variable

Meaning

Value

$`

Text before the match.

Pi● ist●

$&

Matched text.

3.14159

$'

Text after the match.

,● ungefähr.

$1

Text from capture 1.

3.14159

$2

Text from capture 2.

undef

$3

Text from capture 3.

3.14159

$4

Text from capture 4.

.14159

$+

Highest-numbered participating value among $1, $2 , etc.

.14159

$^N

Last closed capture's text among $1, $2, etc.

3.14159

@-

Array of starting offsets for $1, $2, etc.

(7, 7, undef, 7, 8)

@+

Array of ending offsets for $1, $2 , etc.

(14, 14, undef, 14, 14)

Here are these variables in more detail:

$&

A copy of the text matched by the entire regex. Avoid this variable, like $' and $`, where possible (see The variables $`, $& and $' are “naughty”). $& is never undef after success, but may be empty.

$`

A copy of preceding text. With /g, one might wish $` referred to text since the last attempt, but it does not. $` is never undef after success.

$'

A copy of following text. After success, "$`$&$'" always copies the original subject. (Note: an undefined subject can still match; then "$`$&$'" is empty, not undef, the sole difference.) Also, $' is never undef after success.

$1, $2, $3 ...

Text from the first, second, third, etc. capture. Note that $0 is unrelated: $0 holds the script name. Captures are undef if absent from the regex or not participating in the last match.

Use them after matching, including the replacement of s/.../.../. Code patterns and dynamic constructs may also use them (see The dynamic regex construct). Inside regexes, backreferences such as ˹\1˼ are appropriate instead. See Using $1 inside a regex?.

Compare ˹(\w+)˼ and ˹(\w)+˼ by examining $1. Both match identical text but capture differently. Applied to tubby , $1 becomes tubby in the first case, but y in the second: plus is outside the parentheses and refills $1 with one character each iteration.

Another distinction is between ˹(x)?˼ and ˹(x?)˼. The first makes the whole capture optional, so $1 is undef or ›x‹. The second capture always participates if the regex succeeds, even matching nothing, allowed by ˹x?˼. Thus, for ˹(x?)˼, possible values of $1 are x or empty.

Some examples:

Matching

$1

Matching

$1

"::" =~ m/:(A?):/

empty string

"::" =~ m/:(\w*):/

empty string

"::" =~ m/:(A)?:/

undef

"::" =~ m/:(\w)*:/

undef

":A:" =~ m/:(A?):/

A

":Wort:" =~ m/:(\w*):/

Wort

":A:" =~ m/:(A)?:/

A

":Wort:" =~ m/:(\w)*:/

t

If parentheses only capture, the choice is yours. These examples all match the same text; only the contents of $1 differ.

 

$+

A copy of the explicitly set, highest-numbered $1, $2... variable. In this example,

$url =~ m{
   href \s* = \s*     # Zuerst der »href =«-Teil, dann ...
   (?: "([^"]*)"      # ein String in Anführungszeichen oder ...
     | '([^']*)'      # ein String in Hochkommas oder ...
     | ([^'"<>]+))    # ein ›nackter‹ Wert.
}ix;

the href value is easy to retrieve. Without $+ you must inspect $1, $2 and $3 in order, selecting the non-undef value.

Without participating captures, $+ is undef.

 

$^N

A copy of the last stored $1, $2, etc., corresponding to the capture exited last. It is the special value of $1, $2, etc. Without participating captures, $^N is undef. For $^N, see Emulating named captures.

 

@- and @+

These arrays hold start and end offsets. Their odd names take practice. Element zero describes the entire match. The first element of @-, $-[0], is the starting offset. After

$text = "Version 6 kommt bald raus?";
  .
  . 
  .
$text =~ m/\d+/;

, $-[0] contains 8, so matching begins at character eight, since Perl uses zero-based indices.

The first element of @+, $+[0], gives the ending offset, here 9, after character nine. Use substr($text, $-[0], $+[0] - $-[0]) to obtain matched text if $text is unchanged. This emulates $& without the efficiency problems of $& (see The variables $`, $& and $' are “naughty”). Example using @-:

1 while $zeile =~ s/\t/' ' x (8 - $-[0] % 8)/e;

This expands tabs into spaces. (Note: it handles only ordinary Western text, not multibyte single-width characters like 柇 or accented Unicode characters such as à built from base and combining characters; see Unicode.)

Subsequent array elements describe capture offsets: $-[1] and $+[1] give offsets for $1, $-[2] and $+[2] those of $2, etc.

 

$^R

This is relevant only with code patterns or dynamic regex constructs (see The dynamic regex construct). It holds the last executed code construct's return value. For code patterns in the if part of a conditional, ˹(? if then|else)˼ (see Conditional regular expressions), $^R is not set. Values are saved with states, so backtracking discards returns from code not on the final successful path. Thus, $^R holds the last return value from code participating in the match.

With repeated searches using the /g modifier, all variables update each time. Thus replacement text in s/.../.../g can use $1 for the final iteration's captured text.

 

Using $1 inside a regex?

Perl documentation warns against ˹\1˼ outside regexes; use $1 instead. The variable $1 contains static text from the last match's capture. ˹\1˼ is a true regex metacharacter matching the text captured earlier in this search, specifically when the NFA encounters ˹\1˼ within the regex. Backtracking can change that capture during matching.

Conversely, can $1 or other special variables from the table Special variables available after matching be used as regex operands? Yes, especially in code patterns or dynamic constructs (see The dynamic regex construct). Otherwise they are less useful. $1 in a literal interpolates like any variable before the regex engine even starts, so this is the previous match's value, unrelated to the current search.

  

 

 

 

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