📄 perlre.pod
字号:
=head1 NAME
perlre - Perl regular expressions
=head1 DESCRIPTION
This page describes the syntax of regular expressions in Perl. For a
description of how to I<use> regular expressions in matching
operations, plus various examples of the same, see discussion
of C<m//>, C<s///>, C<qr//> and C<??> in L<perlop/"Regexp Quote-Like Operators">.
The matching operations can have various modifiers. The modifiers
that relate to the interpretation of the regular expression inside
are listed below. For the modifiers that alter the way a regular expression
is used by Perl, see L<perlop/"Regexp Quote-Like Operators"> and
L<perlop/"Gory details of parsing quoted constructs">.
=over 4
=item i
Do case-insensitive pattern matching.
If C<use locale> is in effect, the case map is taken from the current
locale. See L<perllocale>.
=item m
Treat string as multiple lines. That is, change "^" and "$" from matching
at only the very start or end of the string to the start or end of any
line anywhere within the string,
=item s
Treat string as single line. That is, change "." to match any character
whatsoever, even a newline, which it normally would not match.
The C</s> and C</m> modifiers both override the C<$*> setting. That is, no matter
what C<$*> contains, C</s> without C</m> will force "^" to match only at the
beginning of the string and "$" to match only at the end (or just before a
newline at the end) of the string. Together, as /ms, they let the "." match
any character whatsoever, while yet allowing "^" and "$" to match,
respectively, just after and just before newlines within the string.
=item x
Extend your pattern's legibility by permitting whitespace and comments.
=back
These are usually written as "the C</x> modifier", even though the delimiter
in question might not actually be a slash. In fact, any of these
modifiers may also be embedded within the regular expression itself using
the new C<(?...)> construct. See below.
The C</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 C<#>
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 C<#> characters in the pattern (outside of a character
class, where they are unaffected by C</x>), that you'll either have to
escape them 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 L<perlop>.
=head2 Regular Expressions
The patterns used in pattern matching are regular expressions such as
those supplied in the Version 8 regex routines. (In fact, the
routines are derived (distantly) from Henry Spencer's freely
redistributable reimplementation of the V8 routines.)
See L<Version 8 Regular Expressions> for details.
In particular the following metacharacters have their standard I<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 at only the
beginning of the string, the "$" character at 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, 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 C<$*>,
but this practice is now deprecated.)
To facilitate multi-line substitutions, the "." character never matches a
newline unless you use the C</s> modifier, which in effect tells Perl to pretend
the string is a single line--even if it isn't. The C</s> modifier also
overrides the setting of C<$*>, in case you have some (badly behaved) older
code that sets it in another module.
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.) The "*" modifier is equivalent to C<{0,}>, the "+"
modifier to C<{1,}>, and the "?" modifier to C<{0,1}>. n and m are limited
to integral values less than 65536.
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
+? Match 1 or more times
?? Match 0 or 1 time
{n}? Match exactly n times
{n,}? Match at least n times
{n,m}? Match at least n but not more than m times
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 (think of a PDP-11)
\x1B hex char
\c[ control char
\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 C<use locale> is in effect, the case map used by C<\l>, C<\L>, C<\u>
and C<\U> is taken from the current locale. See L<perllocale>.
You cannot include a literal C<$> or C<@> within a C<\Q> sequence.
An unescaped C<$> or C<@> interpolates the corresponding variable,
while escaping will cause the literal string C<\$> to be matched.
You'll need to write something like C<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
A C<\w> matches a single alphanumeric character, not a whole
word. To match a word you'd need to say C<\w+>. If C<use locale> is in
effect, the list of alphabetic characters generated by C<\w> is taken
from the current locale. See L<perllocale>. You may use C<\w>, C<\W>,
C<\s>, C<\S>, C<\d>, and C<\D> within character classes (though not as
either end of a range).
Perl defines the following zero-width assertions:
\b Match a word boundary
\B Match a non-(word boundary)
\A Match only at beginning of string
\Z Match only at end of string, or before newline at the end
\z Match only at end of string
\G Match only where previous m//g left off (works only with /g)
A word boundary (C<\b>) is defined as a spot between two characters that
has a C<\w> on one side of it and a C<\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 C<\W>. (Within character classes C<\b>
represents backspace rather than a word boundary.) The C<\A> and C<\Z> are
just like "^" and "$", except that they won't match multiple times when the
C</m> modifier is used, while "^" and "$" will match at every internal line
boundary. To match the actual end of the string, not ignoring newline,
you can use C<\z>. The C<\G> assertion can be used to chain global
matches (using C<m//g>), as described in
L<perlop/"Regexp Quote-Like Operators">.
It is also useful when writing C<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 C<\G> will match can also be influenced
by using C<pos()> as an lvalue. See L<perlfunc/pos>.
When the bracketing construct C<( ... )> is used, \E<lt>digitE<gt> matches the
digit'th substring. Outside of the pattern, always use "$" instead of "\"
in front of the digit. (While the \E<lt>digitE<gt> notation can on rare occasion work
outside the current pattern, this should not be relied upon. See the
WARNING below.) The scope of $E<lt>digitE<gt> (and C<$`>, C<$&>, and C<$'>)
extends to the end of the enclosing BLOCK or eval string, or to the next
successful pattern match, whichever comes first. If you want to use
parentheses to delimit a subpattern (e.g., a set of alternatives) without
saving it as a subpattern, follow the ( with a ?:.
You may have as many parentheses as you wish. If you have more
than 9 substrings, the variables $10, $11, ... refer to the
corresponding substring. Within the pattern, \10, \11, etc. refer back
to substrings if there have been at least that many left parentheses before
the backreference. Otherwise (for backward compatibility) \10 is the
same as \010, a backspace, and \11 the same as \011, a tab. And so
on. (\1 through \9 are always backreferences.)
C<$+> returns whatever the last bracket match matched. C<$&> returns the
entire matched string. (C<$0> used to return the same thing, but not any
more.) C<$`> returns everything before the matched string. C<$'> returns
everything after the matched string. Examples:
s/^([^ ]*) *([^ ]*)/$2 $1/; # swap first two words
if (/Time: (..):(..):(..)/) {
$hours = $1;
$minutes = $2;
$seconds = $3;
}
Once perl sees that you need one of C<$&>, C<$`> or C<$'> anywhere in
the program, it has to provide them on each and every pattern match.
This can slow your program down. The same mechanism that handles
these provides for the use of $1, $2, etc., so you pay the same price
for each pattern that contains capturing parentheses. But if you never
use $&, etc., in your script, then patterns I<without> capturing
parentheses won't be penalized. So avoid $&, $', and $` if you can,
but if you can't (and some algorithms really appreciate them), once
you've used them once, use them at will, because you've already paid
the price. As of 5.005, $& is not so costly as the other two.
Backslashed metacharacters in Perl are
alphanumeric, such as C<\b>, C<\w>, C<\n>. Unlike some other regular
expression languages, there are no backslashed symbols that aren't
alphanumeric. So anything that looks like \\, \(, \), \E<lt>, \E<gt>,
\{, or \} is always interpreted as a literal character, not a
metacharacter. This was once used in a common idiom to disable or
quote the special meanings of regular expression metacharacters in a
string that you want to use for a pattern. Simply quote all
non-alphanumeric characters:
$pattern =~ s/(\W)/\\$1/g;
Now it is much more common to see either the quotemeta() function or
the C<\Q> escape sequence used to disable all metacharacters' special
meanings like this:
/$unquoted\Q$quoted\E$unquoted/
Perl defines a consistent extension syntax for regular expressions.
The syntax is a pair of parentheses with a question mark as the first
thing within the parentheses (this was a syntax error in older
versions of Perl). The character after the question mark gives the
function of the extension. Several extensions are already supported:
=over 10
=item C<(?#text)>
A comment. The text is ignored. If the C</x> switch is used to enable
whitespace formatting, a simple C<#> will suffice. Note that perl closes
the comment as soon as it sees a C<)>, so there is no way to put a literal
C<)> in the comment.
=item C<(?:pattern)>
=item C<(?imsx-imsx:pattern)>
This is for clustering, not capturing; it groups subexpressions like
"()", but doesn't make backreferences as "()" does. So
@fields = split(/\b(?:a|b|c)\b/)
is like
@fields = split(/\b(a|b|c)\b/)
but doesn't spit out extra fields.
The letters between C<?> and C<:> act as flags modifiers, see
L<C<(?imsx-imsx)>>. In particular,
/(?s-i:more.*than).*million/i
is equivalent to more verbose
/(?:(?s-i)more.*than).*million/i
=item C<(?=pattern)>
A zero-width positive lookahead assertion. For example, C</\w+(?=\t)/>
matches a word followed by a tab, without including the tab in C<$&>.
=item C<(?!pattern)>
A zero-width negative lookahead assertion. For example C</foo(?!bar)/>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -