|
perlre - Perl regular expressions
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 the perlrequick manpage, and a longer tutorial
introduction is available in the perlretut manpage.
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 the perlop manpage.
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 the perlop manpage and
Gory details of parsing quoted constructs in the perlop manpage.
- 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 use locale is in effect, the case map is taken from the current
locale. See the perllocale manpage.
- x
-
Extend your pattern's legibility by permitting whitespace and comments.
- 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 the perlretut manpage for further explanation
of the g and c modifiers.
These are usually written as "the /x modifier", even though the delimiter
in question might not really be a slash. Any of these
modifiers may also be embedded within the regular expression itself using
the (?...) construct. See below.
The /x modifier itself needs a little more explanation. It tells
the regular expression parser to ignore 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
or hex 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 the perlop manpage. Also note that anything inside
a \Q...\E stays unaffected by /x.
The patterns used in Perl pattern matching evolved from the ones 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
[] 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 practice has been 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.
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, 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 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
{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 (?>...) for more details;
possessive quantifiers are just syntactic sugar for that construct. For
instance the above example could also be written as follows:
/"(?>(?:(?>[^"\\]+)|\\.)*)"/
Because patterns are processed as double quoted strings, the following
also work:
\t tab (HT, TAB)
\n newline (LF, NL)
\r return (CR)
\f form feed (FF)
\a alarm (bell) (BEL)
\e escape (think troff) (ESC)
\033 octal char (example: ESC)
\x1B hex char (example: ESC)
\x{263a} long hex char (example: Unicode SMILEY)
\cK control char (example: VT)
\N{name} named Unicode character
\l lowercase next char (think vi)
\u uppercase next char (think vi)
\L lowercase till \E (think vi)
\U uppercase till \E (think vi)
\E end case modification (think vi)
\Q quote (disable) pattern metacharacters till \E
If use locale is in effect, the case map used by \l, \L, \u
and \U is taken from the current locale. See the perllocale manpage. For
documentation of \N{name}, see the charnames manpage.
You cannot include a literal $ or @ within a \Q sequence.
An unescaped $ or @ interpolates the corresponding variable,
while escaping will cause the literal string \$ to be matched.
You'll need to write something like m/\Quser\E\@\Qhost/.
In addition, Perl defines the following:
\w Match a "word" character (alphanumeric plus "_")
\W Match a non-"word" character
\s Match a whitespace character
\S Match a non-whitespace character
\d Match a digit character
\D Match a non-digit character
\pP Match P, named property. Use \p{Prop} for longer names.
\PP Match non-P
\X Match eXtended Unicode "combining character sequence",
equivalent to (?:\PM\pM*)
\C Match a single C char (octet) even under Unicode.
NOTE: breaks up characters into their UTF-8 bytes,
so you may end up with malformed pieces of UTF-8.
Unsupported in lookbehind.
\1 Backreference to a specific group.
'1' may actually be any positive integer.
\g1 Backreference to a specific or previous group,
\g{-1} number may be negative indicating a previous buffer and may
optionally be wrapped in curly brackets for safer parsing.
\g{name} Named backreference
\k<name> Named backreference
\K Keep the stuff left of the \K, don't include it in $&
\v Vertical whitespace
\V Not vertical whitespace
\h Horizontal whitespace
\H Not horizontal whitespace
\R Linebreak
A \w matches a single alphanumeric character (an alphabetic
character, or a decimal digit) or _, not a whole word. Use \w+
to match a string of Perl-identifier characters (which isn't the same
as matching an English word). If use locale is in effect, the list
of alphabetic characters generated by \w is taken from the current
locale. See the perllocale manpage. You may use \w, \W, \s, \S,
\d, and \D within character classes, but they aren't usable
as either end of a range. If any of them precedes or follows a "-",
the "-" is understood literally. If Unicode is in effect, \s matches
also "\x{85}", "\x{2028}", and "\x{2029}". See the perlunicode manpage for more
details about \pP, \PP, \X and the possibility of defining
your own \p and \P properties, and the perluniintro manpage about Unicode
in general.
\R will atomically match a linebreak, including the network line-ending
"\x0D\x0A". Specifically, is exactly equivalent to
(?>\x0D\x0A?|[\x0A-\x0C\x85\x{2028}\x{2029}])
Note: \R has no special meaning inside of a character class;
use \v instead (vertical whitespace).
The POSIX character class syntax
[:class:]
is also available. Note that the [ and ] brackets are literal;
they must always be used within a character class expression.
$string =~ /[[:alpha:]]/;
$string =~ /[:alpha:]/;
The available classes and their backslash equivalents (if available) are
as follows:
alpha
alnum
ascii
blank [1]
cntrl
digit \d
graph
lower
print
punct
space \s [2]
upper
word \w [3]
xdigit
- [1]
-
A GNU extension equivalent to [ \t], "all horizontal whitespace".
- [2]
-
Not exactly equivalent to \s since the [[:space:]] includes
also the (very rare) "vertical tabulator", "\cK" or chr(11) in ASCII.
- [3]
-
A Perl extension, see above.
For example use [:upper:] to match all the uppercase characters.
Note that the [] are part of the [::] construct, not part of the
whole character class. For example:
[01[:alpha:]%]
matches zero, one, any alphabetic character, and the percent sign.
The following equivalences to Unicode \p{} constructs and equivalent
backslash character classes (if available), will hold:
[[:...:]] \p{...} backslash
alpha IsAlpha
alnum IsAlnum
ascii IsASCII
blank
cntrl IsCntrl
digit IsDigit \d
graph IsGraph
lower IsLower
print IsPrint
punct IsPunct
space IsSpace
IsSpacePerl \s
upper IsUpper
word IsWord
xdigit IsXDigit
For example [[:lower:]] and \p{IsLower} are equivalent.
If the utf8 pragma is not used but the locale pragma is, the
classes correlate with the usual isalpha(3) interface (except for
"word" and "blank").
The other named classes are:
- cntrl
-
Any control character. Usually characters that don't produce output as
such but instead control the terminal somehow: for example newline and
backspace are control characters. All characters with ord() less than
32 are usually classified as control characters (assuming ASCII,
the ISO Latin character sets, and Unicode), as is the character with
the ord() value of 127 (DEL).
- graph
-
Any alphanumeric or punctuation (special) character.
- print
-
Any alphanumeric or punctuation (special) character or the space character.
- punct
-
Any punctuation (special) character.
- xdigit
-
Any hexadecimal digit. Though this may feel silly ([0-9A-Fa-f] would
work just fine) it is included for completeness.
You can negate the [::] character classes by prefixing the class name
with a '^'. This is a Perl extension. For example:
POSIX traditional Unicode
[[:^digit:]] \D \P{IsDigit}
[[:^space:]] \S \P{IsSpace}
[[:^word:]] \W \P{IsWord}
Perl respects the POSIX standard in that POSIX character classes are
only supported within a character class. The POSIX character classes
[.cc.] and [=cc=] are recognized but not supported and trying to
use them will cause an error.
|