PERLRE(1) Perl Programmers Reference Guide PERLRE(1)
NAME
perlre - Perl regular expressions
DESCRIPTION
This page describes the syntax of regular expressions in Perl.
If you haven't used regular expressions before, a quick-start introduction is available in perlrequick, and a longer tutorial introduction
is available in perlretut.
For reference on how regular expressions are used in matching operations, plus various examples of the same, see discussions of "m//",
"s///", "qr//" and "??" in "Regexp Quote-Like Operators" in perlop.
Modifiers
Matching operations can have various modifiers. Modifiers that relate to the interpretation of the regular expression inside are listed
below. Modifiers that alter the way a regular expression is used by Perl are detailed in "Regexp Quote-Like Operators" in perlop and "Gory
details of parsing quoted constructs" in perlop.
m Treat string as multiple lines. That is, change "^" and "$" from matching the start or end of the string to matching the start or end
of any line anywhere within the string.
s Treat string as single line. That is, change "." to match any character whatsoever, even a newline, which normally it would not match.
Used together, as "/ms", they let the "." match any character whatsoever, while still allowing "^" and "$" to match, respectively, just
after and just before newlines within the string.
i Do case-insensitive pattern matching.
If locale matching rules are in effect, the case map is taken from the current locale for code points less than 255, and from Unicode
rules for larger code points. However, matches that would cross the Unicode rules/non-Unicode rules boundary (ords 255/256) will not
succeed. See perllocale.
There are a number of Unicode characters that match multiple characters under "/i". For example, "LATIN SMALL LIGATURE FI" should
match the sequence "fi". Perl is not currently able to do this when the multiple characters are in the pattern and are split between
groupings, or when one or more are quantified. Thus
"N{LATIN SMALL LIGATURE FI}" =~ /fi/i; # Matches
"N{LATIN SMALL LIGATURE FI}" =~ /[fi][fi]/i; # Doesn't match!
"N{LATIN SMALL LIGATURE FI}" =~ /fi*/i; # Doesn't match!
# The below doesn't match, and it isn't clear what $1 and $2 would
# be even if it did!!
"N{LATIN SMALL LIGATURE FI}" =~ /(f)(i)/i; # Doesn't match!
Perl doesn't match multiple characters in an inverted bracketed character class, which otherwise could be highly confusing. See
"Negation" in perlrecharclass.
Also, Perl matching doesn't fully conform to the current Unicode "/i" recommendations, which ask that the matching be made upon the NFD
(Normalization Form Decomposed) of the text. However, Unicode is in the process of reconsidering and revising their recommendations.
x Extend your pattern's legibility by permitting whitespace and comments. Details in "/x"
p Preserve the string matched such that ${^PREMATCH}, ${^MATCH}, and ${^POSTMATCH} are available for use after matching.
g and c
Global matching, and keep the Current position after failed matching. Unlike i, m, s and x, these two flags affect the way the regex
is used rather than the regex itself. See "Using regular expressions in Perl" in perlretut for further explanation of the g and c
modifiers.
a, d, l and u
These modifiers, new in 5.14, affect which character-set semantics (Unicode, ASCII, etc.) are used, as described below in "Character
set modifiers".
These are usually written as "the "/x" modifier", even though the delimiter in question might not really be a slash. The modifiers
"/imsxadlup" may also be embedded within the regular expression itself using the "(?...)" construct, see "Extended Patterns" below.
The "/x", "/l", "/u", "/a" and "/d" modifiers need a little more explanation.
/x
"/x" tells the regular expression parser to ignore most whitespace that is neither backslashed nor within a character class. You can use
this to break up your regular expression into (slightly) more readable parts. The "#" character is also treated as a metacharacter
introducing a comment, just as in ordinary Perl code. This also means that if you want real whitespace or "#" characters in the pattern
(outside a character class, where they are unaffected by "/x"), then you'll either have to escape them (using backslashes or "Q...E") or
encode them using octal, hex, or "N{}" escapes. Taken together, these features go a long way towards making Perl's regular expressions
more readable. Note that you have to be careful not to include the pattern delimiter in the comment--perl has no way of knowing you did
not intend to close the pattern early. See the C-comment deletion code in perlop. Also note that anything inside a "Q...E" stays
unaffected by "/x". And note that "/x" doesn't affect space interpretation within a single multi-character construct. For example in
"x{...}", regardless of the "/x" modifier, there can be no spaces. Same for a quantifier such as "{3}" or "{5,}". Similarly, "(?:...)"
can't have a space between the "?" and ":", but can between the "(" and "?". Within any delimiters for such a construct, allowed spaces
are not affected by "/x", and depend on the construct. For example, "x{...}" can't have spaces because hexadecimal numbers don't have
spaces in them. But, Unicode properties can have spaces, so in "p{...}" there can be spaces that follow the Unicode rules, for which see
"Properties accessible through p{} and P{}" in perluniprops.
Character set modifiers
"/d", "/u", "/a", and "/l", available starting in 5.14, are called the character set modifiers; they affect the character set semantics
used for the regular expression.
At any given time, exactly one of these modifiers is in effect. Once compiled, the behavior doesn't change regardless of what rules are in
effect when the regular expression is executed. And if a regular expression is interpolated into a larger one, the original's rules
continue to apply to it, and only it.
Note that the modifiers affect only pattern matching, and do not extend to any replacement done. For example,
s/foo/Ubar/l
will uppercase "bar", but the "/l" does not affect how the "U" operates. If "use locale" is in effect, the "U" will use locale rules; if
"use feature 'unicode_strings'" is in effect, it will use Unicode rules, etc.
/l
means to use the current locale's rules (see perllocale) when pattern matching. For example, "w" will match the "word" characters of that
locale, and "/i" case-insensitive matching will match according to the locale's case folding rules. The locale used will be the one in
effect at the time of execution of the pattern match. This may not be the same as the compilation-time locale, and can differ from one
match to another if there is an intervening call of the setlocale() function.
Perl only supports single-byte locales. This means that code points above 255 are treated as Unicode no matter what locale is in effect.
Under Unicode rules, there are a few case-insensitive matches that cross the 255/256 boundary. These are disallowed under "/l". For
example, 0xFF does not caselessly match the character at 0x178, "LATIN CAPITAL LETTER Y WITH DIAERESIS", because 0xFF may not be "LATIN
SMALL LETTER Y WITH DIAERESIS" in the current locale, and Perl has no way of knowing if that character even exists in the locale, much less
what code point it is.
This modifier may be specified to be the default by "use locale", but see "Which character set modifier is in effect?".
/u
means to use Unicode rules when pattern matching. On ASCII platforms, this means that the code points between 128 and 255 take on their
Latin-1 (ISO-8859-1) meanings (which are the same as Unicode's), whereas in strict ASCII their meanings are undefined. Thus the platform
effectively becomes a Unicode platform, hence, for example, "w" will match any of the more than 100_000 word characters in Unicode.
Unlike most locales, which are specific to a language and country pair, Unicode classifies all the characters that are letters somewhere as
"w". For example, your locale might not think that "LATIN SMALL LETTER ETH" is a letter (unless you happen to speak Icelandic), but
Unicode does. Similarly, all the characters that are decimal digits somewhere in the world will match "d"; this is hundreds, not 10,
possible matches. And some of those digits look like some of the 10 ASCII digits, but mean a different number, so a human could easily
think a number is a different quantity than it really is. For example, "BENGALI DIGIT FOUR" (U+09EA) looks very much like an "ASCII DIGIT
EIGHT" (U+0038). And, "d+", may match strings of digits that are a mixture from different writing systems, creating a security issue.
"num()" in Unicode::UCD can be used to sort this out.
Also, case-insensitive matching works on the full set of Unicode characters. The "KELVIN SIGN", for example matches the letters "k" and
"K"; and "LATIN SMALL LIGATURE FF" matches the sequence "ff", which, if you're not prepared, might make it look like a hexadecimal
constant, presenting another potential security issue. See <http://unicode.org/reports/tr36> for a detailed discussion of Unicode security
issues.
On the EBCDIC platforms that Perl handles, the native character set is equivalent to Latin-1. Thus this modifier changes behavior only
when the "/i" modifier is also specified, and it turns out it affects only two characters, giving them full Unicode semantics: the "MICRO
SIGN" will match the Greek capital and small letters "MU", otherwise not; and the "LATIN CAPITAL LETTER SHARP S" will match any of "SS",
"Ss", "sS", and "ss", otherwise not.
This modifier may be specified to be the default by "use feature 'unicode_strings", but see "Which character set modifier is in effect?".
/a
is the same as "/u", except that "d", "s", "w", and the Posix character classes are restricted to matching in the ASCII range only.
That is, with this modifier, "d" always means precisely the digits "0" to "9"; "s" means the five characters "[ f
]"; "w" means
the 63 characters "[A-Za-z0-9_]"; and likewise, all the Posix classes such as "[[:print:]]" match only the appropriate ASCII-range
characters.
This modifier is useful for people who only incidentally use Unicode. With it, one can write "d" with confidence that it will only match
ASCII characters, and should the need arise to match beyond ASCII, you can use "p{Digit}", or "p{Word}" for "w". There are similar
"p{...}" constructs that can match white space and Posix classes beyond ASCII. See "POSIX Character Classes" in perlrecharclass.
As you would expect, this modifier causes, for example, "D" to mean the same thing as "[^0-9]"; in fact, all non-ASCII characters match
"D", "S", and "W". "" still means to match at the boundary between "w" and "W", using the "/a" definitions of them (similarly for
"B").
Otherwise, "/a" behaves like the "/u" modifier, in that case-insensitive matching uses Unicode semantics; for example, "k" will match the
Unicode "N{KELVIN SIGN}" under "/i" matching, and code points in the Latin1 range, above ASCII will have Unicode rules when it comes to
case-insensitive matching.
To forbid ASCII/non-ASCII matches (like "k" with "N{KELVIN SIGN}"), specify the "a" twice, for example "/aai" or "/aia"
To reiterate, this modifier provides protection for applications that don't wish to be exposed to all of Unicode. Specifying it twice
gives added protection.
This modifier may be specified to be the default by "use re '/a'" or "use re '/aa'", but see "Which character set modifier is in effect?".
/d
This modifier means to use the "Default" native rules of the platform except when there is cause to use Unicode rules instead, as follows:
1. the target string is encoded in UTF-8; or
2. the pattern is encoded in UTF-8; or
3. the pattern explicitly mentions a code point that is above 255 (say by "x{100}"); or
4. the pattern uses a Unicode name ("N{...}"); or
5. the pattern uses a Unicode property ("p{...}")
Another mnemonic for this modifier is "Depends", as the rules actually used depend on various things, and as a result you can get
unexpected results. See "The "Unicode Bug"" in perlunicode.
On ASCII platforms, the native rules are ASCII, and on EBCDIC platforms (at least the ones that Perl handles), they are Latin-1.
Here are some examples of how that works on an ASCII platform:
$str = "xDF"; # $str is not in UTF-8 format.
$str =~ /^w/; # No match, as $str isn't in UTF-8 format.
$str .= "x{0e0b}"; # Now $str is in UTF-8 format.
$str =~ /^w/; # Match! $str is now in UTF-8 format.
chop $str;
$str =~ /^w/; # Still a match! $str remains in UTF-8 format.
Which character set modifier is in effect?
Which of these modifiers is in effect at any given point in a regular expression depends on a fairly complex set of interactions. As
explained below in "Extended Patterns" it is possible to explicitly specify modifiers that apply only to portions of a regular expression.
The innermost always has priority over any outer ones, and one applying to the whole expression has priority over any of the default
settings that are described in the remainder of this section.
The "use re '/foo'" pragma can be used to set default modifiers (including these) for regular expressions compiled within its scope. This
pragma has precedence over the other pragmas listed below that change the defaults.
Otherwise, "use locale" sets the default modifier to "/l"; and "use feature 'unicode_strings" or "use 5.012" (or higher) set the default to
"/u" when not in the same scope as either "use locale" or "use bytes". Unlike the mechanisms mentioned above, these affect operations
besides regular expressions pattern matching, and so give more consistent results with other operators, including using "U", "l", etc. in
substitution replacements.
If none of the above apply, for backwards compatibility reasons, the "/d" modifier is the one in effect by default. As this can lead to
unexpected results, it is best to specify which other rule set should be used.
Character set modifier behavior prior to Perl 5.14
Prior to 5.14, there were no explicit modifiers, but "/l" was implied for regexes compiled within the scope of "use locale", and "/d" was
implied otherwise. However, interpolating a regex into a larger regex would ignore the original compilation in favor of whatever was in
effect at the time of the second compilation. There were a number of inconsistencies (bugs) with the "/d" modifier, where Unicode rules
would be used when inappropriate, and vice versa. "p{}" did not imply Unicode rules, and neither did all occurrences of "N{}", until
5.12.
Regular Expressions
Metacharacters
The patterns used in Perl pattern matching evolved from those supplied in the Version 8 regex routines. (The routines are derived
(distantly) from Henry Spencer's freely redistributable reimplementation of the V8 routines.) See "Version 8 Regular Expressions" for
details.
In particular the following metacharacters have their standard egrep-ish meanings:
Quote the next metacharacter
^ Match the beginning of the line
. Match any character (except newline)
$ Match the end of the line (or before newline at the end)
| Alternation
() Grouping
[] Bracketed Character class
By default, the "^" character is guaranteed to match only the beginning of the string, the "$" character only the end (or before the
newline at the end), and Perl does certain optimizations with the assumption that the string contains only one line. Embedded newlines
will not be matched by "^" or "$". You may, however, wish to treat a string as a multi-line buffer, such that the "^" will match after any
newline within the string (except if the newline is the last character in the string), and "$" will match before any newline. At the cost
of a little more overhead, you can do this by using the /m modifier on the pattern match operator. (Older programs did this by setting $*,
but this option was removed in perl 5.9.)
To simplify multi-line substitutions, the "." character never matches a newline unless you use the "/s" modifier, which in effect tells
Perl to pretend the string is a single line--even if it isn't.
Quantifiers
The following standard quantifiers are recognized:
* Match 0 or more times
+ Match 1 or more times
? Match 1 or 0 times
{n} Match exactly n times
{n,} Match at least n times
{n,m} Match at least n but not more than m times
(If a curly bracket occurs in any other context and does not form part of a backslashed sequence like "x{...}", it is treated as a regular
character. In particular, the lower bound is not optional.) The "*" quantifier is equivalent to "{0,}", the "+" quantifier to "{1,}", and
the "?" quantifier to "{0,1}". n and m are limited to non-negative integral values less than a preset limit defined when perl is built.
This is usually 32766 on the most common platforms. The actual limit can be seen in the error message generated by code such as this:
$_ **= $_ , / {$_} / for 2 .. 42;
By default, a quantified subpattern is "greedy", that is, it will match as many times as possible (given a particular starting location)
while still allowing the rest of the pattern to match. If you want it to match the minimum number of times possible, follow the quantifier
with a "?". Note that the meanings don't change, just the "greediness":
*? Match 0 or more times, not greedily
+? Match 1 or more times, not greedily
?? Match 0 or 1 time, not greedily
{n}? Match exactly n times, not greedily (redundant)
{n,}? Match at least n times, not greedily
{n,m}? Match at least n but not more than m times, not greedily
By default, when a quantified subpattern does not allow the rest of the overall pattern to match, Perl will backtrack. However, this
behaviour is sometimes undesirable. Thus Perl provides the "possessive" quantifier form as well.
*+ Match 0 or more times and give nothing back
++ Match 1 or more times and give nothing back
?+ Match 0 or 1 time and give nothing back
{n}+ Match exactly n times and give nothing back (redundant)
{n,}+ Match at least n times and give nothing back
{n,m}+ Match at least n but not more than m times and give nothing back
For instance,
'aaaa' =~ /a++a/
will never match, as the "a++" will gobble up all the "a"'s in the string and won't leave any for the remaining part of the pattern. This
feature can be extremely useful to give perl hints about where it shouldn't backtrack. For instance, the typical "match a double-quoted
string" problem can be most efficiently performed when written as:
/"(?:[^"\]++|\.)*+"/
as we know that if the final quote does not match, backtracking will not help. See the independent subexpression ""(?>pattern)"" for more
details; possessive quantifiers are just syntactic sugar for that construct. For instance the above example could also be written as
follows:
/"(?>(?:(?>[^"\]+)|\.)*)"/
Escape sequences
Because patterns are processed as double-quoted strings, the following also work:
tab (HT, TAB)
newline (LF, NL)
return (CR)
f form feed (FF)
a alarm (bell) (BEL)
e escape (think troff) (ESC)
cK control char (example: VT)
x{}, x00 character whose ordinal is the given hexadecimal number
N{name} named Unicode character or character sequence
N{U+263D} Unicode character (example: FIRST QUARTER MOON)
o{}, 00 character whose ordinal is the given octal number
l lowercase next char (think vi)
u uppercase next char (think vi)
L lowercase till E (think vi)
U uppercase till E (think vi)
Q quote (disable) pattern metacharacters till E
E end either case modification or quoted section, think vi
Details are in "Quote and Quote-like Operators" in perlop.
Character Classes and other Special Escapes
In addition, Perl defines the following:
Sequence Note Description
[...] [1] Match a character according to the rules of the
bracketed character class defined by the "...".
Example: [a-z] matches "a" or "b" or "c" ... or "z"
[[:...:]] [2] Match a character according to the rules of the POSIX
character class "..." within the outer bracketed
character class. Example: [[:upper:]] matches any
uppercase character.
w [3] Match a "word" character (alphanumeric plus "_", plus
other connector punctuation chars plus Unicode
marks)
W [3] Match a non-"word" character
s [3] Match a whitespace character
S [3] Match a non-whitespace character
d [3] Match a decimal digit character
D [3] Match a non-digit character
pP [3] Match P, named property. Use p{Prop} for longer names
PP [3] Match non-P
X [4] Match Unicode "eXtended grapheme cluster"
C Match a single C-language char (octet) even if that is
part of a larger UTF-8 character. Thus it breaks up
characters into their UTF-8 bytes, so you may end up
with malformed pieces of UTF-8. Unsupported in
lookbehind.
1 [5] Backreference to a specific capture group or buffer.
'1' may actually be any positive integer.
g1 [5] Backreference to a specific or previous group,
g{-1} [5] The number may be negative indicating a relative
previous group and may optionally be wrapped in
curly brackets for safer parsing.
g{name} [5] Named backreference
k<name> [5] Named backreference
K [6] Keep the stuff left of the K, don't include it in $&
N [7] Any character but
(experimental). Not affected by
/s modifier
v [3] Vertical whitespace
V [3] Not vertical whitespace
h [3] Horizontal whitespace
H [3] Not horizontal whitespace
R [4] Linebreak
[1] See "Bracketed Character Classes" in perlrecharclass for details.
[2] See "POSIX Character Classes" in perlrecharclass for details.
[3] See "Backslash sequences" in perlrecharclass for details.
[4] See "Misc" in perlrebackslash for details.
[5] See "Capture groups" below for details.
[6] See "Extended Patterns" below for details.
[7] Note that "N" has two meanings. When of the form "N{NAME}", it matches the character or character sequence whose name is "NAME"; and
similarly when of the form "N{U+hex}", it matches the character whose Unicode code point is hex. Otherwise it matches any character
but "
".
Assertions
Perl defines the following zero-width assertions:
Match a word boundary
B Match except at a word boundary
A Match only at beginning of string
Match only at end of string, or before newline at the end
z Match only at end of string
G Match only at pos() (e.g. at the end-of-match position
of prior m//g)
A word boundary ("") is a spot between two characters that has a "w" on one side of it and a "W" on the other side of it (in either
order), counting the imaginary characters off the beginning and end of the string as matching a "W". (Within character classes ""
represents backspace rather than a word boundary, just as it normally does in any double-quoted string.) The "A" and "" are just like
"^" and "$", except that they won't match multiple times when the "/m" modifier is used, while "^" and "$" will match at every internal
line boundary. To match the actual end of the string and not ignore an optional trailing newline, use "z".
The "G" assertion can be used to chain global matches (using "m//g"), as described in "Regexp Quote-Like Operators" in perlop. It is also
useful when writing "lex"-like scanners, when you have several patterns that you want to match against consequent substrings of your
string; see the previous reference. The actual location where "G" will match can also be influenced by using "pos()" as an lvalue: see
"pos" in perlfunc. Note that the rule for zero-length matches (see "Repeated Patterns Matching a Zero-length Substring") is modified
somewhat, in that contents to the left of "G" are not counted when determining the length of the match. Thus the following will not match
forever:
my $string = 'ABC';
pos($string) = 1;
while ($string =~ /(.G)/g) {
print $1;
}
It will print 'A' and then terminate, as it considers the match to be zero-width, and thus will not match at the same position twice in a
row.
It is worth noting that "G" improperly used can result in an infinite loop. Take care when using patterns that include "G" in an
alternation.
Capture groups
The bracketing construct "( ... )" creates capture groups (also referred to as capture buffers). To refer to the current contents of a
group later on, within the same pattern, use "g1" (or "g{1}") for the first, "g2" (or "g{2}") for the second, and so on. This is
called a backreference.
There is no limit to the number of captured substrings that you may use. Groups are numbered with the leftmost open parenthesis being
number 1, etc. If a group did not match, the associated backreference won't match either. (This can happen if the group is optional, or in
a different branch of an alternation.) You can omit the "g", and write "1", etc, but there are some issues with this form, described
below.
You can also refer to capture groups relatively, by using a negative number, so that "g-1" and "g{-1}" both refer to the immediately
preceding capture group, and "g-2" and "g{-2}" both refer to the group before it. For example:
/
(Y) # group 1
( # group 2
(X) # group 3
g{-1} # backref to group 3
g{-3} # backref to group 1
)
/x
would match the same as "/(Y) ( (X) g3 g1 )/x". This allows you to interpolate regexes into larger regexes and not have to worry about
the capture groups being renumbered.
You can dispense with numbers altogether and create named capture groups. The notation is "(?<name>...)" to declare and "g{name}" to
reference. (To be compatible with .Net regular expressions, "g{name}" may also be written as "k{name}", "k<name>" or "k'name'".) name
must not begin with a number, nor contain hyphens. When different groups within the same pattern have the same name, any reference to that
name assumes the leftmost defined group. Named groups count in absolute and relative numbering, and so can also be referred to by those
numbers. (It's possible to do things with named capture groups that would otherwise require "(??{})".)
Capture group contents are dynamically scoped and available to you outside the pattern until the end of the enclosing block or until the
next successful match, whichever comes first. (See "Compound Statements" in perlsyn.) You can refer to them by absolute number (using
"$1" instead of "g1", etc); or by name via the "%+" hash, using "$+{name}".
Braces are required in referring to named capture groups, but are optional for absolute or relative numbered ones. Braces are safer when
creating a regex by concatenating smaller strings. For example if you have "qr/$a$b/", and $a contained "g1", and $b contained "37", you
would get "/g137/" which is probably not what you intended.
The "g" and "k" notations were introduced in Perl 5.10.0. Prior to that there were no named nor relative numbered capture groups.
Absolute numbered groups were referred to using "1", "2", etc., and this notation is still accepted (and likely always will be). But it
leads to some ambiguities if there are more than 9 capture groups, as "10" could mean either the tenth capture group, or the character
whose ordinal in octal is 010 (a backspace in ASCII). Perl resolves this ambiguity by interpreting "10" as a backreference only if at
least 10 left parentheses have opened before it. Likewise "11" is a backreference only if at least 11 left parentheses have opened before
it. And so on. "1" through "9" are always interpreted as backreferences. There are several examples below that illustrate these
perils. You can avoid the ambiguity by always using "g{}" or "g" if you mean capturing groups; and for octal constants always using
"o{}", or for "