<LI><A HREF="#creating custom re engines">Creating custom RE engines</A></LI>
</UL>
<LI><A HREF="#bugs">BUGS</A></LI>
<LI><A HREF="#see also">SEE ALSO</A></LI>
</UL>
<!-- INDEX END -->
<HR>
<P>
<H1><A NAME="name">NAME</A></H1>
<P>perlre - Perl regular expressions</P>
<P>
<HR>
<H1><A NAME="description">DESCRIPTION</A></H1>
<P>This page describes the syntax of regular expressions in Perl. For a
description of how to <EM>use</EM> regular expressions in matching
operations, plus various examples of the same, see discussions
of <CODE>m//</CODE>, <CODE>s///</CODE>, <CODE>qr//</CODE> and <CODE>??</CODE> in <A HREF="../../lib/Pod/perlop.html#regexp quotelike operators">Regexp Quote-Like Operators in the perlop manpage</A>.</P>
<P>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 <A HREF="../../lib/Pod/perlop.html#regexp quotelike operators">Regexp Quote-Like Operators in the perlop manpage</A> and
<A HREF="../../lib/Pod/perlop.html#gory details of parsing quoted constructs">Gory details of parsing quoted constructs in the perlop manpage</A>.</P>
<DL>
<DT><STRONG><A NAME="item_i">i</A></STRONG><BR>
<DD>
Do case-insensitive pattern matching.
<P>If <CODE>use locale</CODE> is in effect, the case map is taken from the current
locale. See <A HREF="../../lib/Pod/perllocale.html">the perllocale manpage</A>.</P>
<P></P>
<DT><STRONG><A NAME="item_m">m</A></STRONG><BR>
<DD>
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.
<P></P>
<DT><STRONG><A NAME="item_s">s</A></STRONG><BR>
<DD>
Treat string as single line. That is, change ``.'' to match any character
whatsoever, even a newline, which normally it would not match.
<P>The <CODE>/s</CODE> and <CODE>/m</CODE> modifiers both override the <CODE>$*</CODE> setting. That
is, no matter what <CODE>$*</CODE> contains, <CODE>/s</CODE> without <CODE>/m</CODE> 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.</P>
<P></P>
<DT><STRONG><A NAME="item_x">x</A></STRONG><BR>
<DD>
Extend your pattern's legibility by permitting whitespace and comments.
<P></P></DL>
<P>These are usually written as ``the <CODE>/x</CODE> 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 <CODE>(?...)</CODE> construct. See below.</P>
<P>The <CODE>/x</CODE> 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 <CODE>#</CODE>
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 <CODE>#</CODE> characters in the pattern (outside a character
class, where they are unaffected by <CODE>/x</CODE>), 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 <A HREF="../../lib/Pod/perlop.html">the perlop manpage</A>.</P>
<P>The patterns used in Perl pattern matching derive from supplied in
the Version 8 regex routines. (The routines are derived
(distantly) from Henry Spencer's freely redistributable reimplementation
of the V8 routines.) See <A HREF="#version 8 regular expressions">Version 8 Regular Expressions</A> for
details.</P>
<P>In particular the following metacharacters have their standard <EM>egrep</EM>-ish
meanings:</P>
<PRE>
\ 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</PRE>
<P>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, 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 <CODE>$*</CODE>,
but this practice is now deprecated.)</P>
<P>To simplify multi-line substitutions, the ``.'' character never matches a
newline unless you use the <CODE>/s</CODE> modifier, which in effect tells Perl to pretend
the string is a single line--even if it isn't. The <CODE>/s</CODE> modifier also
overrides the setting of <CODE>$*</CODE>, in case you have some (badly behaved) older
code that sets it in another module.</P>
<P>The following standard quantifiers are recognized:</P>
<PRE>
* 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</PRE>
<P>(If a curly bracket occurs in any other context, it is treated
as a regular character.) The ``*'' modifier is equivalent to <CODE>{0,}</CODE>, the ``+''
modifier to <CODE>{1,}</CODE>, and the ``?'' modifier to <CODE>{0,1}</CODE>. 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:</P>
<PRE>
$_ **= $_ , / {$_} / for 2 .. 42;</PRE>
<P>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'':</P>
<PRE>
*? 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</PRE>
<P>Because patterns are processed as double quoted strings, the following
also work:</P>
<PRE>
\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
\x{263a} wide hex char (Unicode SMILEY)
\c[ control char
\N{name} named 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</PRE>
<P>If <CODE>use locale</CODE> is in effect, the case map used by <CODE>\l</CODE>, <CODE>\L</CODE>, <CODE>\u</CODE>
and <CODE>\U</CODE> is taken from the current locale. See <A HREF="../../lib/Pod/perllocale.html">the perllocale manpage</A>. For
documentation of <CODE>\N{name}</CODE>, see <A HREF="../../lib/charnames.html">the charnames manpage</A>.</P>
<P>You cannot include a literal <CODE>$</CODE> or <CODE>@</CODE> within a <CODE>\Q</CODE> sequence.
An unescaped <CODE>$</CODE> or <CODE>@</CODE> interpolates the corresponding variable,
while escaping will cause the literal string <CODE>\$</CODE> to be matched.
You'll need to write something like <CODE>m/\Quser\E\@\Qhost/</CODE>.</P>
<P>In addition, Perl defines the following:</P>
<PRE>
\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 C<(?:\PM\pM*)>
\C Match a single C char (octet) even under utf8.</PRE>
<P>A <CODE>\w</CODE> matches a single alphanumeric character, not a whole word.
Use <CODE>\w+</CODE> to match a string of Perl-identifier characters (which isn't
the same as matching an English word). If <CODE>use locale</CODE> is in effect, the
list of alphabetic characters generated by <CODE>\w</CODE> is taken from the
current locale. See <A HREF="../../lib/Pod/perllocale.html">the perllocale manpage</A>. You may use <CODE>\w</CODE>, <CODE>\W</CODE>, <CODE>\s</CODE>, <CODE>\S</CODE>,
<CODE>\d</CODE>, and <CODE>\D</CODE> within character classes, but if you try to use them
as endpoints of a range, that's not a range, the ``-'' is understood literally.
See <A HREF="../../lib/utf8.html">the utf8 manpage</A> for details about <CODE>\pP</CODE>, <CODE>\PP</CODE>, and <CODE>\X</CODE>.</P>
<P>The POSIX character class syntax</P>
<PRE>
[:class:]</PRE>
<P>is also available. The available classes and their backslash
equivalents (if available) are as follows:</P>
<PRE>
alpha
alnum
ascii
cntrl
digit \d
graph
lower
print
punct
space \s
upper
word \w
xdigit</PRE>
<P>For example use <CODE>[:upper:]</CODE> to match all the uppercase characters.
Note that the <CODE>[]</CODE> are part of the <CODE>[::]</CODE> construct, not part of the whole
character class. For example:</P>
<PRE>
[01[:alpha:]%]</PRE>
<P>matches one, zero, any alphabetic character, and the percentage sign.</P>
<P>If the <CODE>utf8</CODE> pragma is used, the following equivalences to Unicode
\p{} constructs hold:</P>
<PRE>
alpha IsAlpha
alnum IsAlnum
ascii IsASCII
cntrl IsCntrl
digit IsDigit
graph IsGraph
lower IsLower
print IsPrint
punct IsPunct
space IsSpace
upper IsUpper
word IsWord
xdigit IsXDigit</PRE>
<P>For example <CODE>[:lower:]</CODE> and <CODE>\p{IsLower}</CODE> are equivalent.</P>
<P>If the <CODE>utf8</CODE> pragma is not used but the <CODE>locale</CODE> pragma is, the
classes correlate with the <CODE>isalpha(3)</CODE> interface (except for `word',
which is a Perl extension, mirroring <CODE>\w</CODE>).</P>
<P>The assumedly non-obviously named classes are:</P>
Any hexadecimal digit. Though this may feel silly (/0-9a-f/i would
work just fine) it is included for completeness.
<P></P></DL>
<P>You can negate the [::] character classes by prefixing the class name
with a '^'. This is a Perl extension. For example:</P>
<PRE>
POSIX trad. Perl utf8 Perl</PRE>
<PRE>
[:^digit:] \D \P{IsDigit}
[:^space:] \S \P{IsSpace}
[:^word:] \W \P{IsWord}</PRE>
<P>The POSIX character classes [.cc.] and [=cc=] are recognized but
<STRONG>not</STRONG> supported and trying to use them will cause an error.</P>
<P>Perl defines the following zero-width assertions:</P>
<PRE>
\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 at pos() (e.g. at the end-of-match position
of prior m//g)</PRE>
<P>A word boundary (<CODE>\b</CODE>) is a spot between two characters
that has a <CODE>\w</CODE> on one side of it and a <CODE>\W</CODE> on the other side
of it (in either order), counting the imaginary characters off the
beginning and end of the string as matching a <CODE>\W</CODE>. (Within
character classes <CODE>\b</CODE> represents backspace rather than a word
boundary, just as it normally does in any double-quoted string.)
The <CODE>\A</CODE> and <CODE>\Z</CODE> are just like ``^'' and ``$'', except that they
won't match multiple times when the <CODE>/m</CODE> 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 <CODE>\z</CODE>.</P>
<P>The <CODE>\G</CODE> assertion can be used to chain global matches (using
<CODE>m//g</CODE>), as described in <A HREF="../../lib/Pod/perlop.html#regexp quotelike operators">Regexp Quote-Like Operators in the perlop manpage</A>.
It is also useful when writing <CODE>lex</CODE>-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 <CODE>\G</CODE> will match can also be influenced by using <A HREF="../../lib/Pod/perlfunc.html#item_pos"><CODE>pos()</CODE></A> as
an lvalue. See <A HREF="../../lib/Pod/perlfunc.html#pos">pos in the perlfunc manpage</A>.</P>
<P>The bracketing construct <CODE>( ... )</CODE> creates capture buffers. To
refer to the digit'th buffer use \<digit> within the
match. Outside the match use ``$'' instead of ``\''. (The
\<digit> notation works in certain circumstances outside
the match. See the warning below about \1 vs $1 for details.)
Referring back to another part of the match is called a
<EM>backreference</EM>.</P>
<P>There is no limit to the number of captured substrings that you may
use. However Perl also uses \10, \11, etc. as aliases for \010,
\011, etc. (Recall that 0 means octal, so \011 is the 9'th ASCII
character, a tab.) 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.``</P>
<P>Examples:</P>
<PRE>
s/^([^ ]*) *([^ ]*)/$2 $1/; # swap first two words</PRE>
<PRE>
if (/(.)\1/) { # find first doubled char
print "'$1' is the first doubled character\n";
}</PRE>
<PRE>
if (/Time: (..):(..):(..)/) { # parse out values
$hours = $1;
$minutes = $2;
$seconds = $3;
}</PRE>
<P>Several special variables also refer back to portions of the previous
match. <CODE>$+</CODE> returns whatever the last bracket match matched.
<CODE>$&</CODE> returns the entire matched string. (At one point <CODE>$0</CODE> did
also, but now it returns the name of the program.) <CODE>$`</CODE> returns
everything before the matched string. And <CODE>$'</CODE> returns everything
after the matched string.</P>
<P>The numbered variables ($1, $2, $3, etc.) and the related punctuation
set (<CODE><$+</CODE>, <CODE>$&</CODE>, <CODE>$`</CODE>, and <CODE>$'</CODE>) are all dynamically scoped
until the end of the enclosing block or until the next successful
match, whichever comes first. (See <A HREF="../../lib/Pod/perlsyn.html#compound statements">Compound Statements in the perlsyn manpage</A>.)</P>
<P><STRONG>WARNING</STRONG>: Once Perl sees that you need one of <CODE>$&</CODE>, <CODE>$`</CODE>, or
<CODE>$'</CODE> anywhere in the program, it has to provide them for every
pattern match. This may substantially slow your program. Perl
uses the same mechanism to produce $1, $2, etc, so you also pay a
price for each pattern that contains capturing parentheses. (To
avoid this cost while retaining the grouping behaviour, use the
extended regular expression <CODE>(?: ... )</CODE> instead.) But if you never
use <CODE>$&</CODE>, <CODE>$`</CODE> or <CODE>$'</CODE>, then patterns <EM>without</EM> capturing
parentheses will not be penalized. So avoid <CODE>$&</CODE>, <CODE>$'</CODE>, and <CODE>$`</CODE>
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, <CODE>$&</CODE> is not so costly as the
other two.</P>
<P>Backslashed metacharacters in Perl are alphanumeric, such as <CODE>\b</CODE>,
<CODE>\w</CODE>, <CODE>\n</CODE>. Unlike some other regular expression languages, there
are no backslashed symbols that aren't alphanumeric. So anything
that looks like \\, \(, \), \<, \>, \{, 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:</P>
<PRE>
$pattern =~ s/(\W)/\\$1/g;</PRE>
<P>Today it is more common to use the <A HREF="../../lib/Pod/perlfunc.html#item_quotemeta"><CODE>quotemeta()</CODE></A> function or the <CODE>\Q</CODE>
metaquoting escape sequence to disable all metacharacters' special
meanings like this:</P>
<PRE>
/$unquoted\Q$quoted\E$unquoted/</PRE>
<P>Beware that if you put literal backslashes (those not inside
interpolated variables) between <CODE>\Q</CODE> and <CODE>\E</CODE>, double-quotish
backslash interpolation may lead to confusing results. If you
<EM>need</EM> to use literal backslashes within <CODE>\Q...\E</CODE>,
consult <A HREF="../../lib/Pod/perlop.html#gory details of parsing quoted constructs">Gory details of parsing quoted constructs in the perlop manpage</A>.</P>
<STRONG>WARNING</STRONG>: This extended regular expression feature is considered
highly experimental, and may be changed or deleted without notice.
<P>This zero-width assertion evaluate any embedded Perl code. It
always succeeds, and its <CODE>code</CODE> is not interpolated. Currently,
the rules to determine where the <CODE>code</CODE> ends are somewhat convoluted.</P>
<P>The <CODE>code</CODE> is properly scoped in the following sense: If the assertion
is backtracked (compare <A HREF="#backtracking">Backtracking</A>), all changes introduced after
<A HREF="../../lib/Pod/perlfunc.html#item_local"><CODE>local</CODE></A>ization are undone, so that</P>
<PRE>
$_ = 'a' x 8;
m<
(?{ $cnt = 0 }) # Initialize $cnt.
(
a
(?{
local $cnt = $cnt + 1; # Update $cnt, backtracking-safe.
})
)*
aaaa
(?{ $res = $cnt }) # On success copy to non-localized
# location.
>x;</PRE>
<P>will set <CODE>$res = 4</CODE>. Note that after the match, $cnt returns to the globally
introduced value, because the scopes that restrict <A HREF="../../lib/Pod/perlfunc.html#item_local"><CODE>local</CODE></A> operators
are unwound.</P>
<P>This assertion may be used as a <A HREF="#item_%28%3F%28condition%29yes%2Dpattern%7Cno%2Dpattern%"><CODE>(?(condition)yes-pattern|no-pattern)</CODE></A>
switch. If <EM>not</EM> used in this way, the result of evaluation of
<CODE>code</CODE> is put into the special variable <CODE>$^R</CODE>. This happens
immediately, so <CODE>$^R</CODE> can be used from other <A HREF="#item_%28%3F%7B_code_%7D%29"><CODE>(?{ code })</CODE></A> assertions
inside the same regular expression.</P>
<P>The assignment to <CODE>$^R</CODE> above is properly localized, so the old
value of <CODE>$^R</CODE> is restored if the assertion is backtracked; compare
<A HREF="#backtracking">Backtracking</A>.</P>
<P>For reasons of security, this construct is forbidden if the regular
expression involves run-time interpolation of variables, unless the
perilous <CODE>use re 'eval'</CODE> pragma has been used (see <A HREF="../../lib/re.html">the re manpage</A>), or the
variables contain results of <CODE>qr//</CODE> operator (see
<A HREF="../../lib/Pod/perlop.html#qr/string/imosx">qr/STRING/imosx in the perlop manpage</A>).</P>
<P>This restriction is because of the wide-spread and remarkably convenient
custom of using run-time determined strings as patterns. For example:</P>
<PRE>
$re = <>;
chomp $re;
$string =~ /$re/;</PRE>
<P>Before Perl knew how to execute interpolated code within a pattern,
this operation was completely safe from a security point of view,
although it could raise an exception from an illegal pattern. If
you turn on the <CODE>use re 'eval'</CODE>, though, it is no longer secure,
so you should only do so if you are also using taint checking.
Better yet, use the carefully constrained evaluation within a Safe
module. See <A HREF="../../lib/Pod/perlsec.html">the perlsec manpage</A> for details about both these mechanisms.</P>
Same as <A HREF="#item_S"><CODE>S{0,1}</CODE></A>, <A HREF="#item_S"><CODE>S{0,BIG_NUMBER}</CODE></A>, <A HREF="#item_S"><CODE>S{1,BIG_NUMBER}</CODE></A> respectively.
Recall that which of <CODE>yes-pattern</CODE> or <CODE>no-pattern</CODE> actually matches is
already determined. The ordering of the matches is the same as for the
chosen subexpression.
<P></P></DL>
<P>The above recipes describe the ordering of matches <EM>at a given position</EM>.
One more rule is needed to understand how a match is determined for the
whole regular expression: a match at an earlier position is always better
than a match at a later position.</P>
<P>
<H2><A NAME="creating custom re engines">Creating custom RE engines</A></H2>
<P>Overloaded constants (see <A HREF="../../lib/overload.html">the overload manpage</A>) provide a simple way to extend
the functionality of the RE engine.</P>
<P>Suppose that we want to enable a new RE escape-sequence <CODE>\Y|</CODE> which
matches at boundary between white-space characters and non-whitespace
characters. Note that <CODE>(?=\S)(?<!\S)|(?!\S)(?<=\S)</CODE> matches exactly
at these positions, so we want to have each <CODE>\Y|</CODE> in the place of the
more complicated version. We can create a module <CODE>customre</CODE> to do
this:</P>
<PRE>
package customre;
use overload;</PRE>
<PRE>
sub import {
shift;
die "No argument to customre::import allowed" if @_;
overload::constant 'qr' => \&convert;
}</PRE>
<PRE>
sub invalid { die "/$_[0]/: invalid escape '\\$_[1]'"}</PRE>
<PRE>
my %rules = ( '\\' => '\\',
'Y|' => qr/(?=\S)(?<!\S)|(?!\S)(?<=\S)/ );
sub convert {
my $re = shift;
$re =~ s{
\\ ( \\ | Y . )
}
{ $rules{$1} or invalid($re,$1) }sgex;
return $re;
}</PRE>
<P>Now <CODE>use customre</CODE> enables the new escape in constant regular
expressions, i.e., those without any runtime variable interpolations.
As documented in <A HREF="../../lib/overload.html">the overload manpage</A>, this conversion will work only over
literal parts of regular expressions. For <CODE>\Y|$re\Y|</CODE> the variable
part of this regular expression needs to be converted explicitly
(but only if the special meaning of <CODE>\Y|</CODE> should be enabled inside $re):</P>
<PRE>
use customre;
$re = <>;
chomp $re;
$re = customre::convert $re;
/\Y|$re\Y|/;</PRE>
<P>
<HR>
<H1><A NAME="bugs">BUGS</A></H1>
<P>This document varies from difficult to understand to completely
and utterly opaque. The wandering prose riddled with jargon is
hard to fathom in several places.</P>
<P>This document needs a rewrite that separates the tutorial content
from the reference content.</P>
<P>
<HR>
<H1><A NAME="see also">SEE ALSO</A></H1>
<P><A HREF="../../lib/Pod/perlop.html#regexp quotelike operators">Regexp Quote-Like Operators in the perlop manpage</A>.</P>
<P><A HREF="../../lib/Pod/perlop.html#gory details of parsing quoted constructs">Gory details of parsing quoted constructs in the perlop manpage</A>.</P>