Plan 9 from Bell Labs’s /usr/web/sources/contrib/gabidiaz/root/sys/man/1perl/perlre

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sh \" Subsection heading
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings.  \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote.  | will give a
.\" real vertical bar.  \*(C+ will give a nicer C++.  Capital omega is used to
.\" do unbreakable dashes and therefore won't be available.  \*(C` and \*(C'
.\" expand to `' in nroff, nothing in troff, for use with C<>.
.tr \(*W-|\(bv\*(Tr
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
.    ds -- \(*W-
.    ds PI pi
.    if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
.    if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\"  diablo 12 pitch
.    ds L" ""
.    ds R" ""
.    ds C` ""
.    ds C' ""
'br\}
.el\{\
.    ds -- \|\(em\|
.    ds PI \(*p
.    ds L" ``
.    ds R" ''
'br\}
.\"
.\" If the F register is turned on, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
.\" entries marked with X<> in POD.  Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.if \nF \{\
.    de IX
.    tm Index:\\$1\t\\n%\t"\\$2"
..
.    nr % 0
.    rr F
.\}
.\"
.\" For nroff, turn off justification.  Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.hy 0
.if n .na
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear.  Run.  Save yourself.  No user-serviceable parts.
.    \" fudge factors for nroff and troff
.if n \{\
.    ds #H 0
.    ds #V .8m
.    ds #F .3m
.    ds #[ \f1
.    ds #] \fP
.\}
.if t \{\
.    ds #H ((1u-(\\\\n(.fu%2u))*.13m)
.    ds #V .6m
.    ds #F 0
.    ds #[ \&
.    ds #] \&
.\}
.    \" simple accents for nroff and troff
.if n \{\
.    ds ' \&
.    ds ` \&
.    ds ^ \&
.    ds , \&
.    ds ~ ~
.    ds /
.\}
.if t \{\
.    ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
.    ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
.    ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
.    ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
.    ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
.    ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
.    \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
.    \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
.    \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
.    ds : e
.    ds 8 ss
.    ds o a
.    ds d- d\h'-1'\(ga
.    ds D- D\h'-1'\(hy
.    ds th \o'bp'
.    ds Th \o'LP'
.    ds ae ae
.    ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "PERLRE 1"
.TH PERLRE 1 "2002-11-24" "perl v5.8.0" "Perl Programmers Reference Guide"
.SH "NAME"
perlre \- Perl regular expressions
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
This page describes the syntax of regular expressions in Perl.  
.PP
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.
.PP
For reference on how regular expressions are used in matching
operations, plus various examples of the same, see discussions of
\&\f(CW\*(C`m//\*(C'\fR, \f(CW\*(C`s///\*(C'\fR, \f(CW\*(C`qr//\*(C'\fR and \f(CW\*(C`??\*(C'\fR in \*(L"Regexp Quote-Like Operators\*(R" in perlop.
.PP
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 \*(L"Regexp Quote-Like Operators\*(R" in perlop and 
\&\*(L"Gory details of parsing quoted constructs\*(R" in perlop.
.IP "i" 4
.IX Item "i"
Do case-insensitive pattern matching.
.Sp
If \f(CW\*(C`use locale\*(C'\fR is in effect, the case map is taken from the current
locale.  See perllocale.
.IP "m" 4
.IX Item "m"
Treat string as multiple lines.  That is, change \*(L"^\*(R" and \*(L"$\*(R" from matching
the start or end of the string to matching the start or end of any
line anywhere within the string.
.IP "s" 4
.IX Item "s"
Treat string as single line.  That is, change \*(L".\*(R" to match any character
whatsoever, even a newline, which normally it would not match.
.Sp
The \f(CW\*(C`/s\*(C'\fR and \f(CW\*(C`/m\*(C'\fR modifiers both override the \f(CW$*\fR setting.  That
is, no matter what \f(CW$*\fR contains, \f(CW\*(C`/s\*(C'\fR without \f(CW\*(C`/m\*(C'\fR will force
\&\*(L"^\*(R" to match only at the beginning of the string and \*(L"$\*(R" to match
only at the end (or just before a newline at the end) of the string.
Together, as /ms, they let the \*(L".\*(R" match any character whatsoever,
while still allowing \*(L"^\*(R" and \*(L"$\*(R" to match, respectively, just after
and just before newlines within the string.
.IP "x" 4
.IX Item "x"
Extend your pattern's legibility by permitting whitespace and comments.
.PP
These are usually written as "the \f(CW\*(C`/x\*(C'\fR 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 \f(CW\*(C`(?...)\*(C'\fR construct.  See below.
.PP
The \f(CW\*(C`/x\*(C'\fR 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 \f(CW\*(C`#\*(C'\fR
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 \f(CW\*(C`#\*(C'\fR characters in the pattern (outside a character
class, where they are unaffected by \f(CW\*(C`/x\*(C'\fR), 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 perlop.
.Sh "Regular Expressions"
.IX Subsection "Regular Expressions"
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 \*(L"Version 8 Regular Expressions\*(R" for
details.
.PP
In particular the following metacharacters have their standard \fIegrep\fR\-ish
meanings:
.PP
.Vb 7
\&    \e   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
.Ve
.PP
By default, the \*(L"^\*(R" character is guaranteed to match only the
beginning of the string, the \*(L"$\*(R" 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 \*(L"^\*(R" or \*(L"$\*(R".  You may, however, wish to treat a
string as a multi-line buffer, such that the \*(L"^\*(R" will match after any
newline within the string, and \*(L"$\*(R" 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 \f(CW$*\fR,
but this practice is now deprecated.)
.PP
To simplify multi-line substitutions, the \*(L".\*(R" character never matches a
newline unless you use the \f(CW\*(C`/s\*(C'\fR modifier, which in effect tells Perl to pretend
the string is a single line\*(--even if it isn't.  The \f(CW\*(C`/s\*(C'\fR modifier also
overrides the setting of \f(CW$*\fR, in case you have some (badly behaved) older
code that sets it in another module.
.PP
The following standard quantifiers are recognized:
.PP
.Vb 6
\&    *      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
.Ve
.PP
(If a curly bracket occurs in any other context, it is treated
as a regular character.)  The \*(L"*\*(R" modifier is equivalent to \f(CW\*(C`{0,}\*(C'\fR, the \*(L"+\*(R"
modifier to \f(CW\*(C`{1,}\*(C'\fR, and the \*(L"?\*(R" modifier to \f(CW\*(C`{0,1}\*(C'\fR.  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:
.PP
.Vb 1
\&    $_ **= $_ , / {$_} / for 2 .. 42;
.Ve
.PP
By default, a quantified subpattern is \*(L"greedy\*(R", 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 \*(L"?\*(R".  Note
that the meanings don't change, just the \*(L"greediness\*(R":
.PP
.Vb 6
\&    *?     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
.Ve
.PP
Because patterns are processed as double quoted strings, the following
also work:
.PP
.Vb 17
\&    \et          tab                   (HT, TAB)
\&    \en          newline               (LF, NL)
\&    \er          return                (CR)
\&    \ef          form feed             (FF)
\&    \ea          alarm (bell)          (BEL)
\&    \ee          escape (think troff)  (ESC)
\&    \e033        octal char (think of a PDP-11)
\&    \ex1B        hex char
\&    \ex{263a}    wide hex char         (Unicode SMILEY)
\&    \ec[         control char
\&    \eN{name}    named char
\&    \el          lowercase next char (think vi)
\&    \eu          uppercase next char (think vi)
\&    \eL          lowercase till \eE (think vi)
\&    \eU          uppercase till \eE (think vi)
\&    \eE          end case modification (think vi)
\&    \eQ          quote (disable) pattern metacharacters till \eE
.Ve
.PP
If \f(CW\*(C`use locale\*(C'\fR is in effect, the case map used by \f(CW\*(C`\el\*(C'\fR, \f(CW\*(C`\eL\*(C'\fR, \f(CW\*(C`\eu\*(C'\fR
and \f(CW\*(C`\eU\*(C'\fR is taken from the current locale.  See perllocale.  For
documentation of \f(CW\*(C`\eN{name}\*(C'\fR, see charnames.
.PP
You cannot include a literal \f(CW\*(C`$\*(C'\fR or \f(CW\*(C`@\*(C'\fR within a \f(CW\*(C`\eQ\*(C'\fR sequence.
An unescaped \f(CW\*(C`$\*(C'\fR or \f(CW\*(C`@\*(C'\fR interpolates the corresponding variable,
while escaping will cause the literal string \f(CW\*(C`\e$\*(C'\fR to be matched.
You'll need to write something like \f(CW\*(C`m/\eQuser\eE\e@\eQhost/\*(C'\fR.
.PP
In addition, Perl defines the following:
.PP
.Vb 13
\&    \ew  Match a "word" character (alphanumeric plus "_")
\&    \eW  Match a non-"word" character
\&    \es  Match a whitespace character
\&    \eS  Match a non-whitespace character
\&    \ed  Match a digit character
\&    \eD  Match a non-digit character
\&    \epP Match P, named property.  Use \ep{Prop} for longer names.
\&    \ePP Match non-P
\&    \eX  Match eXtended Unicode "combining character sequence",
\&        equivalent to (?:\ePM\epM*)
\&    \eC  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.
.Ve
.PP
A \f(CW\*(C`\ew\*(C'\fR matches a single alphanumeric character (an alphabetic
character, or a decimal digit) or \f(CW\*(C`_\*(C'\fR, not a whole word.  Use \f(CW\*(C`\ew+\*(C'\fR
to match a string of Perl-identifier characters (which isn't the same
as matching an English word).  If \f(CW\*(C`use locale\*(C'\fR is in effect, the list
of alphabetic characters generated by \f(CW\*(C`\ew\*(C'\fR is taken from the current
locale.  See perllocale.  You may use \f(CW\*(C`\ew\*(C'\fR, \f(CW\*(C`\eW\*(C'\fR, \f(CW\*(C`\es\*(C'\fR, \f(CW\*(C`\eS\*(C'\fR,
\&\f(CW\*(C`\ed\*(C'\fR, and \f(CW\*(C`\eD\*(C'\fR within character classes, but if you try to use them
as endpoints of a range, that's not a range, the \*(L"\-\*(R" is understood
literally.  If Unicode is in effect, \f(CW\*(C`\es\*(C'\fR matches also \*(L"\ex{85}\*(R",
\&\*(L"\ex{2028}, and \*(R"\ex{2029}", see perlunicode for more details about
\&\f(CW\*(C`\epP\*(C'\fR, \f(CW\*(C`\ePP\*(C'\fR, and \f(CW\*(C`\eX\*(C'\fR, and perluniintro about Unicode in general.
You can define your own \f(CW\*(C`\ep\*(C'\fR and \f(CW\*(C`\eP\*(C'\fR propreties, see perlunicode.
.PP
The \s-1POSIX\s0 character class syntax
.PP
.Vb 1
\&    [:class:]
.Ve
.PP
is also available.  The available classes and their backslash
equivalents (if available) are as follows:
.PP
.Vb 14
\&    alpha
\&    alnum
\&    ascii
\&    blank               [1]
\&    cntrl
\&    digit       \ed
\&    graph
\&    lower
\&    print
\&    punct
\&    space       \es      [2]
\&    upper
\&    word        \ew      [3]
\&    xdigit
.Ve
.IP "[1]" 4
.IX Item "[1]"
A \s-1GNU\s0 extension equivalent to \f(CW\*(C`[ \et]\*(C'\fR, `all horizontal whitespace'.
.IP "[2]" 4
.IX Item "[2]"
Not exactly equivalent to \f(CW\*(C`\es\*(C'\fR since the \f(CW\*(C`[[:space:]]\*(C'\fR includes
also the (very rare) `vertical tabulator', \*(L"\eck\*(R", chr(11).
.IP "[3]" 4
.IX Item "[3]"
A Perl extension, see above.
.PP
For example use \f(CW\*(C`[:upper:]\*(C'\fR to match all the uppercase characters.
Note that the \f(CW\*(C`[]\*(C'\fR are part of the \f(CW\*(C`[::]\*(C'\fR construct, not part of the
whole character class.  For example:
.PP
.Vb 1
\&    [01[:alpha:]%]
.Ve
.PP
matches zero, one, any alphabetic character, and the percentage sign.
.PP
The following equivalences to Unicode \ep{} constructs and equivalent
backslash character classes (if available), will hold:
.PP
.Vb 1
\&    [:...:]     \ep{...}         backslash
.Ve
.PP
.Vb 15
\&    alpha       IsAlpha
\&    alnum       IsAlnum
\&    ascii       IsASCII
\&    blank       IsSpace
\&    cntrl       IsCntrl
\&    digit       IsDigit        \ed
\&    graph       IsGraph
\&    lower       IsLower
\&    print       IsPrint
\&    punct       IsPunct
\&    space       IsSpace
\&                IsSpacePerl    \es
\&    upper       IsUpper
\&    word        IsWord
\&    xdigit      IsXDigit
.Ve
.PP
For example \f(CW\*(C`[:lower:]\*(C'\fR and \f(CW\*(C`\ep{IsLower}\*(C'\fR are equivalent.
.PP
If the \f(CW\*(C`utf8\*(C'\fR pragma is not used but the \f(CW\*(C`locale\*(C'\fR pragma is, the
classes correlate with the usual \fIisalpha\fR\|(3) interface (except for
`word' and `blank').
.PP
The assumedly non-obviously named classes are:
.IP "cntrl" 4
.IX Item "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 \fIord()\fR less than
32 are most often classified as control characters (assuming \s-1ASCII\s0,
the \s-1ISO\s0 Latin character sets, and Unicode), as is the character with
the \fIord()\fR value of 127 (\f(CW\*(C`DEL\*(C'\fR).
.IP "graph" 4
.IX Item "graph"
Any alphanumeric or punctuation (special) character.
.IP "print" 4
.IX Item "print"
Any alphanumeric or punctuation (special) character or the space character.
.IP "punct" 4
.IX Item "punct"
Any punctuation (special) character.
.IP "xdigit" 4
.IX Item "xdigit"
Any hexadecimal digit.  Though this may feel silly ([0\-9A\-Fa\-f] would
work just fine) it is included for completeness.
.PP
You can negate the [::] character classes by prefixing the class name
with a '^'. This is a Perl extension.  For example:
.PP
.Vb 1
\&    POSIX       traditional Unicode
.Ve
.PP
.Vb 3
\&    [:^digit:]      \eD      \eP{IsDigit}
\&    [:^space:]      \eS      \eP{IsSpace}
\&    [:^word:]       \eW      \eP{IsWord}
.Ve
.PP
Perl respects the \s-1POSIX\s0 standard in that \s-1POSIX\s0 character classes are
only supported within a character class.  The \s-1POSIX\s0 character classes
[.cc.] and [=cc=] are recognized but \fBnot\fR supported and trying to
use them will cause an error.
.PP
Perl defines the following zero-width assertions:
.PP
.Vb 7
\&    \eb  Match a word boundary
\&    \eB  Match a non-(word boundary)
\&    \eA  Match only at beginning of string
\&    \eZ  Match only at end of string, or before newline at the end
\&    \ez  Match only at end of string
\&    \eG  Match only at pos() (e.g. at the end-of-match position
\&        of prior m//g)
.Ve
.PP
A word boundary (\f(CW\*(C`\eb\*(C'\fR) is a spot between two characters
that has a \f(CW\*(C`\ew\*(C'\fR on one side of it and a \f(CW\*(C`\eW\*(C'\fR on the other side
of it (in either order), counting the imaginary characters off the
beginning and end of the string as matching a \f(CW\*(C`\eW\*(C'\fR.  (Within
character classes \f(CW\*(C`\eb\*(C'\fR represents backspace rather than a word
boundary, just as it normally does in any double-quoted string.)
The \f(CW\*(C`\eA\*(C'\fR and \f(CW\*(C`\eZ\*(C'\fR are just like \*(L"^\*(R" and \*(L"$\*(R", except that they
won't match multiple times when the \f(CW\*(C`/m\*(C'\fR modifier is used, while
\&\*(L"^\*(R" and \*(L"$\*(R" will match at every internal line boundary.  To match
the actual end of the string and not ignore an optional trailing
newline, use \f(CW\*(C`\ez\*(C'\fR.
.PP
The \f(CW\*(C`\eG\*(C'\fR assertion can be used to chain global matches (using
\&\f(CW\*(C`m//g\*(C'\fR), as described in \*(L"Regexp Quote-Like Operators\*(R" in perlop.
It is also useful when writing \f(CW\*(C`lex\*(C'\fR\-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 \f(CW\*(C`\eG\*(C'\fR will match can also be influenced by using \f(CW\*(C`pos()\*(C'\fR as
an lvalue: see \*(L"pos\*(R" in perlfunc. Currently \f(CW\*(C`\eG\*(C'\fR is only fully
supported when anchored to the start of the pattern; while it
is permitted to use it elsewhere, as in \f(CW\*(C`/(?<=\eG..)./g\*(C'\fR, some
such uses (\f(CW\*(C`/.\eG/g\*(C'\fR, for example) currently cause problems, and
it is recommended that you avoid such usage for now.
.PP
The bracketing construct \f(CW\*(C`( ... )\*(C'\fR creates capture buffers.  To
refer to the digit'th buffer use \e<digit> within the
match.  Outside the match use \*(L"$\*(R" instead of \*(L"\e\*(R".  (The
\&\e<digit> notation works in certain circumstances outside 
the match.  See the warning below about \e1 vs \f(CW$1\fR for details.)
Referring back to another part of the match is called a
\&\fIbackreference\fR.
.PP
There is no limit to the number of captured substrings that you may
use.  However Perl also uses \e10, \e11, etc. as aliases for \e010,
\&\e011, etc.  (Recall that 0 means octal, so \e011 is the character at
number 9 in your coded character set; which would be the 10th character,
a horizontal tab under \s-1ASCII\s0.)  Perl resolves this 
ambiguity by interpreting \e10 as a backreference only if at least 10 
left parentheses have opened before it.  Likewise \e11 is a 
backreference only if at least 11 left parentheses have opened 
before it.  And so on.  \e1 through \e9 are always interpreted as 
backreferences.
.PP
Examples:
.PP
.Vb 1
\&    s/^([^ ]*) *([^ ]*)/$2 $1/;     # swap first two words
.Ve
.PP
.Vb 3
\&     if (/(.)\e1/) {                 # find first doubled char
\&         print "'$1' is the first doubled character\en";
\&     }
.Ve
.PP
.Vb 5
\&    if (/Time: (..):(..):(..)/) {   # parse out values
\&        $hours = $1;
\&        $minutes = $2;
\&        $seconds = $3;
\&    }
.Ve
.PP
Several special variables also refer back to portions of the previous
match.  \f(CW$+\fR returns whatever the last bracket match matched.
\&\f(CW$&\fR returns the entire matched string.  (At one point \f(CW$0\fR did
also, but now it returns the name of the program.)  \f(CW$`\fR returns
everything before the matched string.  \f(CW$'\fR returns everything
after the matched string. And \f(CW$^N\fR contains whatever was matched by
the most-recently closed group (submatch). \f(CW$^N\fR can be used in
extended patterns (see below), for example to assign a submatch to a
variable. 
.PP
The numbered variables ($1, \f(CW$2\fR, \f(CW$3\fR, etc.) and the related punctuation
set (\f(CW$+\fR, \f(CW$&\fR, \f(CW$`\fR, \f(CW$'\fR, and \f(CW$^N\fR) are all dynamically scoped
until the end of the enclosing block or until the next successful
match, whichever comes first.  (See \*(L"Compound Statements\*(R" in perlsyn.)
.PP
\&\fB\s-1WARNING\s0\fR: Once Perl sees that you need one of \f(CW$&\fR, \f(CW$`\fR, or
\&\f(CW$'\fR 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 \f(CW$1\fR, \f(CW$2\fR, 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 \f(CW\*(C`(?: ... )\*(C'\fR instead.)  But if you never
use \f(CW$&\fR, \f(CW$`\fR or \f(CW$'\fR, then patterns \fIwithout\fR capturing
parentheses will not be penalized.  So avoid \f(CW$&\fR, \f(CW$'\fR, and \f(CW$`\fR
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, \f(CW$&\fR is not so costly as the
other two.
.PP
Backslashed metacharacters in Perl are alphanumeric, such as \f(CW\*(C`\eb\*(C'\fR,
\&\f(CW\*(C`\ew\*(C'\fR, \f(CW\*(C`\en\*(C'\fR.  Unlike some other regular expression languages, there
are no backslashed symbols that aren't alphanumeric.  So anything
that looks like \e\e, \e(, \e), \e<, \e>, \e{, or \e} 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\-\*(L"word\*(R" characters:
.PP
.Vb 1
\&    $pattern =~ s/(\eW)/\e\e$1/g;
.Ve
.PP
(If \f(CW\*(C`use locale\*(C'\fR is set, then this depends on the current locale.)
Today it is more common to use the \fIquotemeta()\fR function or the \f(CW\*(C`\eQ\*(C'\fR
metaquoting escape sequence to disable all metacharacters' special
meanings like this:
.PP
.Vb 1
\&    /$unquoted\eQ$quoted\eE$unquoted/
.Ve
.PP
Beware that if you put literal backslashes (those not inside
interpolated variables) between \f(CW\*(C`\eQ\*(C'\fR and \f(CW\*(C`\eE\*(C'\fR, double-quotish
backslash interpolation may lead to confusing results.  If you
\&\fIneed\fR to use literal backslashes within \f(CW\*(C`\eQ...\eE\*(C'\fR,
consult \*(L"Gory details of parsing quoted constructs\*(R" in perlop.
.Sh "Extended Patterns"
.IX Subsection "Extended Patterns"
Perl also defines a consistent extension syntax for features not
found in standard tools like \fBawk\fR and \fBlex\fR.  The syntax is a
pair of parentheses with a question mark as the first thing within
the parentheses.  The character after the question mark indicates
the extension.
.PP
The stability of these extensions varies widely.  Some have been
part of the core language for many years.  Others are experimental
and may change without warning or be completely removed.  Check
the documentation on an individual feature to verify its current
status.
.PP
A question mark was chosen for this and for the minimal-matching
construct because 1) question marks are rare in older regular
expressions, and 2) whenever you see one, you should stop and
\&\*(L"question\*(R" exactly what is going on.  That's psychology...
.ie n .IP """(?#text)""" 10
.el .IP "\f(CW(?#text)\fR" 10
.IX Item "(?#text)"
A comment.  The text is ignored.  If the \f(CW\*(C`/x\*(C'\fR modifier enables
whitespace formatting, a simple \f(CW\*(C`#\*(C'\fR will suffice.  Note that Perl closes
the comment as soon as it sees a \f(CW\*(C`)\*(C'\fR, so there is no way to put a literal
\&\f(CW\*(C`)\*(C'\fR in the comment.
.ie n .IP """(?imsx\-imsx)""" 10
.el .IP "\f(CW(?imsx\-imsx)\fR" 10
.IX Item "(?imsx-imsx)"
One or more embedded pattern-match modifiers, to be turned on (or
turned off, if preceded by \f(CW\*(C`\-\*(C'\fR) for the remainder of the pattern or
the remainder of the enclosing pattern group (if any). This is
particularly useful for dynamic patterns, such as those read in from a
configuration file, read in as an argument, are specified in a table
somewhere, etc.  Consider the case that some of which want to be case
sensitive and some do not.  The case insensitive ones need to include
merely \f(CW\*(C`(?i)\*(C'\fR at the front of the pattern.  For example:
.Sp
.Vb 2
\&    $pattern = "foobar";
\&    if ( /$pattern/i ) { }
.Ve
.Sp
.Vb 1
\&    # more flexible:
.Ve
.Sp
.Vb 2
\&    $pattern = "(?i)foobar";
\&    if ( /$pattern/ ) { }
.Ve
.Sp
These modifiers are restored at the end of the enclosing group. For example,
.Sp
.Vb 1
\&    ( (?i) blah ) \es+ \e1
.Ve
.Sp
will match a repeated (\fIincluding the case\fR!) word \f(CW\*(C`blah\*(C'\fR in any
case, assuming \f(CW\*(C`x\*(C'\fR modifier, and no \f(CW\*(C`i\*(C'\fR modifier outside this
group.
.ie n .IP """(?:pattern)""" 10
.el .IP "\f(CW(?:pattern)\fR" 10
.IX Item "(?:pattern)"
.PD 0
.ie n .IP """(?imsx\-imsx:pattern)""" 10
.el .IP "\f(CW(?imsx\-imsx:pattern)\fR" 10
.IX Item "(?imsx-imsx:pattern)"
.PD
This is for clustering, not capturing; it groups subexpressions like
\&\*(L"()\*(R", but doesn't make backreferences as \*(L"()\*(R" does.  So
.Sp
.Vb 1
\&    @fields = split(/\eb(?:a|b|c)\eb/)
.Ve
.Sp
is like
.Sp
.Vb 1
\&    @fields = split(/\eb(a|b|c)\eb/)
.Ve
.Sp
but doesn't spit out extra fields.  It's also cheaper not to capture
characters if you don't need to.
.Sp
Any letters between \f(CW\*(C`?\*(C'\fR and \f(CW\*(C`:\*(C'\fR act as flags modifiers as with
\&\f(CW\*(C`(?imsx\-imsx)\*(C'\fR.  For example, 
.Sp
.Vb 1
\&    /(?s-i:more.*than).*million/i
.Ve
.Sp
is equivalent to the more verbose
.Sp
.Vb 1
\&    /(?:(?s-i)more.*than).*million/i
.Ve
.ie n .IP """(?=pattern)""" 10
.el .IP "\f(CW(?=pattern)\fR" 10
.IX Item "(?=pattern)"
A zero-width positive look-ahead assertion.  For example, \f(CW\*(C`/\ew+(?=\et)/\*(C'\fR
matches a word followed by a tab, without including the tab in \f(CW$&\fR.
.ie n .IP """(?!pattern)""" 10
.el .IP "\f(CW(?!pattern)\fR" 10
.IX Item "(?!pattern)"
A zero-width negative look-ahead assertion.  For example \f(CW\*(C`/foo(?!bar)/\*(C'\fR
matches any occurrence of \*(L"foo\*(R" that isn't followed by \*(L"bar\*(R".  Note
however that look-ahead and look-behind are \s-1NOT\s0 the same thing.  You cannot
use this for look\-behind.
.Sp
If you are looking for a \*(L"bar\*(R" that isn't preceded by a \*(L"foo\*(R", \f(CW\*(C`/(?!foo)bar/\*(C'\fR
will not do what you want.  That's because the \f(CW\*(C`(?!foo)\*(C'\fR is just saying that
the next thing cannot be \*(L"foo\*(R"\-\-and it's not, it's a \*(L"bar\*(R", so \*(L"foobar\*(R" will
match.  You would have to do something like \f(CW\*(C`/(?!foo)...bar/\*(C'\fR for that.   We
say \*(L"like\*(R" because there's the case of your \*(L"bar\*(R" not having three characters
before it.  You could cover that this way: \f(CW\*(C`/(?:(?!foo)...|^.{0,2})bar/\*(C'\fR.
Sometimes it's still easier just to say:
.Sp
.Vb 1
\&    if (/bar/ && $` !~ /foo$/)
.Ve
.Sp
For look-behind see below.
.ie n .IP """(?<=pattern)""" 10
.el .IP "\f(CW(?<=pattern)\fR" 10
.IX Item "(?<=pattern)"
A zero-width positive look-behind assertion.  For example, \f(CW\*(C`/(?<=\et)\ew+/\*(C'\fR
matches a word that follows a tab, without including the tab in \f(CW$&\fR.
Works only for fixed-width look\-behind.
.ie n .IP """(?<!pattern)""" 10
.el .IP "\f(CW(?<!pattern)\fR" 10
.IX Item "(?<!pattern)"
A zero-width negative look-behind assertion.  For example \f(CW\*(C`/(?<!bar)foo/\*(C'\fR
matches any occurrence of \*(L"foo\*(R" that does not follow \*(L"bar\*(R".  Works
only for fixed-width look\-behind.
.ie n .IP """(?{ code })""" 10
.el .IP "\f(CW(?{ code })\fR" 10
.IX Item "(?{ code })"
\&\fB\s-1WARNING\s0\fR: This extended regular expression feature is considered
highly experimental, and may be changed or deleted without notice.
.Sp
This zero-width assertion evaluate any embedded Perl code.  It
always succeeds, and its \f(CW\*(C`code\*(C'\fR is not interpolated.  Currently,
the rules to determine where the \f(CW\*(C`code\*(C'\fR ends are somewhat convoluted.
.Sp
This feature can be used together with the special variable \f(CW$^N\fR to
capture the results of submatches in variables without having to keep
track of the number of nested parentheses. For example:
.Sp
.Vb 3
\&  $_ = "The brown fox jumps over the lazy dog";
\&  /the (\eS+)(?{ $color = $^N }) (\eS+)(?{ $animal = $^N })/i;
\&  print "color = $color, animal = $animal\en";
.Ve
.Sp
The \f(CW\*(C`code\*(C'\fR is properly scoped in the following sense: If the assertion
is backtracked (compare \*(L"Backtracking\*(R"), all changes introduced after
\&\f(CW\*(C`local\*(C'\fRization are undone, so that
.Sp
.Vb 13
\&  $_ = '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;
.Ve
.Sp
will set \f(CW\*(C`$res = 4\*(C'\fR.  Note that after the match, \f(CW$cnt\fR returns to the globally
introduced value, because the scopes that restrict \f(CW\*(C`local\*(C'\fR operators
are unwound.
.Sp
This assertion may be used as a \f(CW\*(C`(?(condition)yes\-pattern|no\-pattern)\*(C'\fR
switch.  If \fInot\fR used in this way, the result of evaluation of
\&\f(CW\*(C`code\*(C'\fR is put into the special variable \f(CW$^R\fR.  This happens
immediately, so \f(CW$^R\fR can be used from other \f(CW\*(C`(?{ code })\*(C'\fR assertions
inside the same regular expression.
.Sp
The assignment to \f(CW$^R\fR above is properly localized, so the old
value of \f(CW$^R\fR is restored if the assertion is backtracked; compare
\&\*(L"Backtracking\*(R".
.Sp
For reasons of security, this construct is forbidden if the regular
expression involves run-time interpolation of variables, unless the
perilous \f(CW\*(C`use re 'eval'\*(C'\fR pragma has been used (see re), or the
variables contain results of \f(CW\*(C`qr//\*(C'\fR operator (see
\&\*(L"qr/STRING/imosx\*(R" in perlop).  
.Sp
This restriction is because of the wide-spread and remarkably convenient
custom of using run-time determined strings as patterns.  For example:
.Sp
.Vb 3
\&    $re = <>;
\&    chomp $re;
\&    $string =~ /$re/;
.Ve
.Sp
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 \f(CW\*(C`use re 'eval'\*(C'\fR, 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 perlsec for details about both these mechanisms.
.ie n .IP """(??{ code })""" 10
.el .IP "\f(CW(??{ code })\fR" 10
.IX Item "(??{ code })"
\&\fB\s-1WARNING\s0\fR: This extended regular expression feature is considered
highly experimental, and may be changed or deleted without notice.
A simplified version of the syntax may be introduced for commonly
used idioms.
.Sp
This is a \*(L"postponed\*(R" regular subexpression.  The \f(CW\*(C`code\*(C'\fR is evaluated
at run time, at the moment this subexpression may match.  The result
of evaluation is considered as a regular expression and matched as
if it were inserted instead of this construct.
.Sp
The \f(CW\*(C`code\*(C'\fR is not interpolated.  As before, the rules to determine
where the \f(CW\*(C`code\*(C'\fR ends are currently somewhat convoluted.
.Sp
The following pattern matches a parenthesized group:
.Sp
.Vb 9
\&  $re = qr{
\&             \e(
\&             (?:
\&                (?> [^()]+ )    # Non-parens without backtracking
\&              |
\&                (??{ $re })     # Group with matching parens
\&             )*
\&             \e)
\&          }x;
.Ve
.ie n .IP """(?>pattern)""" 10
.el .IP "\f(CW(?>pattern)\fR" 10
.IX Item "(?>pattern)"
\&\fB\s-1WARNING\s0\fR: This extended regular expression feature is considered
highly experimental, and may be changed or deleted without notice.
.Sp
An \*(L"independent\*(R" subexpression, one which matches the substring
that a \fIstandalone\fR \f(CW\*(C`pattern\*(C'\fR would match if anchored at the given
position, and it matches \fInothing other than this substring\fR.  This
construct is useful for optimizations of what would otherwise be
\&\*(L"eternal\*(R" matches, because it will not backtrack (see \*(L"Backtracking\*(R").
It may also be useful in places where the \*(L"grab all you can, and do not
give anything back\*(R" semantic is desirable.
.Sp
For example: \f(CW\*(C`^(?>a*)ab\*(C'\fR will never match, since \f(CW\*(C`(?>a*)\*(C'\fR
(anchored at the beginning of string, as above) will match \fIall\fR
characters \f(CW\*(C`a\*(C'\fR at the beginning of string, leaving no \f(CW\*(C`a\*(C'\fR for
\&\f(CW\*(C`ab\*(C'\fR to match.  In contrast, \f(CW\*(C`a*ab\*(C'\fR will match the same as \f(CW\*(C`a+b\*(C'\fR,
since the match of the subgroup \f(CW\*(C`a*\*(C'\fR is influenced by the following
group \f(CW\*(C`ab\*(C'\fR (see \*(L"Backtracking\*(R").  In particular, \f(CW\*(C`a*\*(C'\fR inside
\&\f(CW\*(C`a*ab\*(C'\fR will match fewer characters than a standalone \f(CW\*(C`a*\*(C'\fR, since
this makes the tail match.
.Sp
An effect similar to \f(CW\*(C`(?>pattern)\*(C'\fR may be achieved by writing
\&\f(CW\*(C`(?=(pattern))\e1\*(C'\fR.  This matches the same substring as a standalone
\&\f(CW\*(C`a+\*(C'\fR, and the following \f(CW\*(C`\e1\*(C'\fR eats the matched string; it therefore
makes a zero-length assertion into an analogue of \f(CW\*(C`(?>...)\*(C'\fR.
(The difference between these two constructs is that the second one
uses a capturing group, thus shifting ordinals of backreferences
in the rest of a regular expression.)
.Sp
Consider this pattern:
.Sp
.Vb 8
\&    m{ \e(
\&          ( 
\&            [^()]+              # x+
\&          | 
\&            \e( [^()]* \e)
\&          )+
\&       \e) 
\&     }x
.Ve
.Sp
That will efficiently match a nonempty group with matching parentheses
two levels deep or less.  However, if there is no such group, it
will take virtually forever on a long string.  That's because there
are so many different ways to split a long string into several
substrings.  This is what \f(CW\*(C`(.+)+\*(C'\fR is doing, and \f(CW\*(C`(.+)+\*(C'\fR is similar
to a subpattern of the above pattern.  Consider how the pattern
above detects no-match on \f(CW\*(C`((()aaaaaaaaaaaaaaaaaa\*(C'\fR in several
seconds, but that each extra letter doubles this time.  This
exponential performance will make it appear that your program has
hung.  However, a tiny change to this pattern
.Sp
.Vb 8
\&    m{ \e( 
\&          ( 
\&            (?> [^()]+ )        # change x+ above to (?> x+ )
\&          | 
\&            \e( [^()]* \e)
\&          )+
\&       \e) 
\&     }x
.Ve
.Sp
which uses \f(CW\*(C`(?>...)\*(C'\fR matches exactly when the one above does (verifying
this yourself would be a productive exercise), but finishes in a fourth
the time when used on a similar string with 1000000 \f(CW\*(C`a\*(C'\fRs.  Be aware,
however, that this pattern currently triggers a warning message under
the \f(CW\*(C`use warnings\*(C'\fR pragma or \fB\-w\fR switch saying it
\&\f(CW"matches null string many times in regex"\fR.
.Sp
On simple groups, such as the pattern \f(CW\*(C`(?> [^()]+ )\*(C'\fR, a comparable
effect may be achieved by negative look\-ahead, as in \f(CW\*(C`[^()]+ (?! [^()] )\*(C'\fR.
This was only 4 times slower on a string with 1000000 \f(CW\*(C`a\*(C'\fRs.
.Sp
The \*(L"grab all you can, and do not give anything back\*(R" semantic is desirable
in many situations where on the first sight a simple \f(CW\*(C`()*\*(C'\fR looks like
the correct solution.  Suppose we parse text with comments being delimited
by \f(CW\*(C`#\*(C'\fR followed by some optional (horizontal) whitespace.  Contrary to
its appearance, \f(CW\*(C`#[ \et]*\*(C'\fR \fIis not\fR the correct subexpression to match
the comment delimiter, because it may \*(L"give up\*(R" some whitespace if
the remainder of the pattern can be made to match that way.  The correct
answer is either one of these:
.Sp
.Vb 2
\&    (?>#[ \et]*)
\&    #[ \et]*(?![ \et])
.Ve
.Sp
For example, to grab non-empty comments into \f(CW$1\fR, one should use either
one of these:
.Sp
.Vb 2
\&    / (?> \e# [ \et]* ) (        .+ ) /x;
\&    /     \e# [ \et]*   ( [^ \et] .* ) /x;
.Ve
.Sp
Which one you pick depends on which of these expressions better reflects
the above specification of comments.
.ie n .IP """(?(condition)yes\-pattern|no\-pattern)""" 10
.el .IP "\f(CW(?(condition)yes\-pattern|no\-pattern)\fR" 10
.IX Item "(?(condition)yes-pattern|no-pattern)"
.PD 0
.ie n .IP """(?(condition)yes\-pattern)""" 10
.el .IP "\f(CW(?(condition)yes\-pattern)\fR" 10
.IX Item "(?(condition)yes-pattern)"
.PD
\&\fB\s-1WARNING\s0\fR: This extended regular expression feature is considered
highly experimental, and may be changed or deleted without notice.
.Sp
Conditional expression.  \f(CW\*(C`(condition)\*(C'\fR should be either an integer in
parentheses (which is valid if the corresponding pair of parentheses
matched), or look\-ahead/look\-behind/evaluate zero-width assertion.
.Sp
For example:
.Sp
.Vb 4
\&    m{ ( \e( )? 
\&       [^()]+ 
\&       (?(1) \e) ) 
\&     }x
.Ve
.Sp
matches a chunk of non\-parentheses, possibly included in parentheses
themselves.
.Sh "Backtracking"
.IX Subsection "Backtracking"
\&\s-1NOTE:\s0 This section presents an abstract approximation of regular
expression behavior.  For a more rigorous (and complicated) view of
the rules involved in selecting a match among possible alternatives,
see \*(L"Combining pieces together\*(R".
.PP
A fundamental feature of regular expression matching involves the
notion called \fIbacktracking\fR, which is currently used (when needed)
by all regular expression quantifiers, namely \f(CW\*(C`*\*(C'\fR, \f(CW\*(C`*?\*(C'\fR, \f(CW\*(C`+\*(C'\fR,
\&\f(CW\*(C`+?\*(C'\fR, \f(CW\*(C`{n,m}\*(C'\fR, and \f(CW\*(C`{n,m}?\*(C'\fR.  Backtracking is often optimized
internally, but the general principle outlined here is valid.
.PP
For a regular expression to match, the \fIentire\fR regular expression must
match, not just part of it.  So if the beginning of a pattern containing a
quantifier succeeds in a way that causes later parts in the pattern to
fail, the matching engine backs up and recalculates the beginning
part\*(--that's why it's called backtracking.
.PP
Here is an example of backtracking:  Let's say you want to find the
word following \*(L"foo\*(R" in the string \*(L"Food is on the foo table.\*(R":
.PP
.Vb 4
\&    $_ = "Food is on the foo table.";
\&    if ( /\eb(foo)\es+(\ew+)/i ) {
\&        print "$2 follows $1.\en";
\&    }
.Ve
.PP
When the match runs, the first part of the regular expression (\f(CW\*(C`\eb(foo)\*(C'\fR)
finds a possible match right at the beginning of the string, and loads up
\&\f(CW$1\fR with \*(L"Foo\*(R".  However, as soon as the matching engine sees that there's
no whitespace following the \*(L"Foo\*(R" that it had saved in \f(CW$1\fR, it realizes its
mistake and starts over again one character after where it had the
tentative match.  This time it goes all the way until the next occurrence
of \*(L"foo\*(R". The complete regular expression matches this time, and you get
the expected output of \*(L"table follows foo.\*(R"
.PP
Sometimes minimal matching can help a lot.  Imagine you'd like to match
everything between \*(L"foo\*(R" and \*(L"bar\*(R".  Initially, you write something
like this:
.PP
.Vb 4
\&    $_ =  "The food is under the bar in the barn.";
\&    if ( /foo(.*)bar/ ) {
\&        print "got <$1>\en";
\&    }
.Ve
.PP
Which perhaps unexpectedly yields:
.PP
.Vb 1
\&  got <d is under the bar in the >
.Ve
.PP
That's because \f(CW\*(C`.*\*(C'\fR was greedy, so you get everything between the
\&\fIfirst\fR \*(L"foo\*(R" and the \fIlast\fR \*(L"bar\*(R".  Here it's more effective
to use minimal matching to make sure you get the text between a \*(L"foo\*(R"
and the first \*(L"bar\*(R" thereafter.
.PP
.Vb 2
\&    if ( /foo(.*?)bar/ ) { print "got <$1>\en" }
\&  got <d is under the >
.Ve
.PP
Here's another example: let's say you'd like to match a number at the end
of a string, and you also want to keep the preceding part of the match.
So you write this:
.PP
.Vb 4
\&    $_ = "I have 2 numbers: 53147";
\&    if ( /(.*)(\ed*)/ ) {                                # Wrong!
\&        print "Beginning is <$1>, number is <$2>.\en";
\&    }
.Ve
.PP
That won't work at all, because \f(CW\*(C`.*\*(C'\fR was greedy and gobbled up the
whole string. As \f(CW\*(C`\ed*\*(C'\fR can match on an empty string the complete
regular expression matched successfully.
.PP
.Vb 1
\&    Beginning is <I have 2 numbers: 53147>, number is <>.
.Ve
.PP
Here are some variants, most of which don't work:
.PP
.Vb 11
\&    $_ = "I have 2 numbers: 53147";
\&    @pats = qw{
\&        (.*)(\ed*)
\&        (.*)(\ed+)
\&        (.*?)(\ed*)
\&        (.*?)(\ed+)
\&        (.*)(\ed+)$
\&        (.*?)(\ed+)$
\&        (.*)\eb(\ed+)$
\&        (.*\eD)(\ed+)$
\&    };
.Ve
.PP
.Vb 8
\&    for $pat (@pats) {
\&        printf "%-12s ", $pat;
\&        if ( /$pat/ ) {
\&            print "<$1> <$2>\en";
\&        } else {
\&            print "FAIL\en";
\&        }
\&    }
.Ve
.PP
That will print out:
.PP
.Vb 8
\&    (.*)(\ed*)    <I have 2 numbers: 53147> <>
\&    (.*)(\ed+)    <I have 2 numbers: 5314> <7>
\&    (.*?)(\ed*)   <> <>
\&    (.*?)(\ed+)   <I have > <2>
\&    (.*)(\ed+)$   <I have 2 numbers: 5314> <7>
\&    (.*?)(\ed+)$  <I have 2 numbers: > <53147>
\&    (.*)\eb(\ed+)$ <I have 2 numbers: > <53147>
\&    (.*\eD)(\ed+)$ <I have 2 numbers: > <53147>
.Ve
.PP
As you see, this can be a bit tricky.  It's important to realize that a
regular expression is merely a set of assertions that gives a definition
of success.  There may be 0, 1, or several different ways that the
definition might succeed against a particular string.  And if there are
multiple ways it might succeed, you need to understand backtracking to
know which variety of success you will achieve.
.PP
When using look-ahead assertions and negations, this can all get even
trickier.  Imagine you'd like to find a sequence of non-digits not
followed by \*(L"123\*(R".  You might try to write that as
.PP
.Vb 4
\&    $_ = "ABC123";
\&    if ( /^\eD*(?!123)/ ) {              # Wrong!
\&        print "Yup, no 123 in $_\en";
\&    }
.Ve
.PP
But that isn't going to match; at least, not the way you're hoping.  It
claims that there is no 123 in the string.  Here's a clearer picture of
why that pattern matches, contrary to popular expectations:
.PP
.Vb 2
\&    $x = 'ABC123' ;
\&    $y = 'ABC445' ;
.Ve
.PP
.Vb 2
\&    print "1: got $1\en" if $x =~ /^(ABC)(?!123)/ ;
\&    print "2: got $1\en" if $y =~ /^(ABC)(?!123)/ ;
.Ve
.PP
.Vb 2
\&    print "3: got $1\en" if $x =~ /^(\eD*)(?!123)/ ;
\&    print "4: got $1\en" if $y =~ /^(\eD*)(?!123)/ ;
.Ve
.PP
This prints
.PP
.Vb 3
\&    2: got ABC
\&    3: got AB
\&    4: got ABC
.Ve
.PP
You might have expected test 3 to fail because it seems to a more
general purpose version of test 1.  The important difference between
them is that test 3 contains a quantifier (\f(CW\*(C`\eD*\*(C'\fR) and so can use
backtracking, whereas test 1 will not.  What's happening is
that you've asked \*(L"Is it true that at the start of \f(CW$x\fR, following 0 or more
non\-digits, you have something that's not 123?\*(R"  If the pattern matcher had
let \f(CW\*(C`\eD*\*(C'\fR expand to \*(L"\s-1ABC\s0\*(R", this would have caused the whole pattern to
fail.
.PP
The search engine will initially match \f(CW\*(C`\eD*\*(C'\fR with \*(L"\s-1ABC\s0\*(R".  Then it will
try to match \f(CW\*(C`(?!123\*(C'\fR with \*(L"123\*(R", which fails.  But because
a quantifier (\f(CW\*(C`\eD*\*(C'\fR) has been used in the regular expression, the
search engine can backtrack and retry the match differently
in the hope of matching the complete regular expression.
.PP
The pattern really, \fIreally\fR wants to succeed, so it uses the
standard pattern back-off-and-retry and lets \f(CW\*(C`\eD*\*(C'\fR expand to just \*(L"\s-1AB\s0\*(R" this
time.  Now there's indeed something following \*(L"\s-1AB\s0\*(R" that is not
\&\*(L"123\*(R".  It's \*(L"C123\*(R", which suffices.
.PP
We can deal with this by using both an assertion and a negation.
We'll say that the first part in \f(CW$1\fR must be followed both by a digit
and by something that's not \*(L"123\*(R".  Remember that the look-aheads
are zero-width expressions\*(--they only look, but don't consume any
of the string in their match.  So rewriting this way produces what
you'd expect; that is, case 5 will fail, but case 6 succeeds:
.PP
.Vb 2
\&    print "5: got $1\en" if $x =~ /^(\eD*)(?=\ed)(?!123)/ ;
\&    print "6: got $1\en" if $y =~ /^(\eD*)(?=\ed)(?!123)/ ;
.Ve
.PP
.Vb 1
\&    6: got ABC
.Ve
.PP
In other words, the two zero-width assertions next to each other work as though
they're ANDed together, just as you'd use any built-in assertions:  \f(CW\*(C`/^$/\*(C'\fR
matches only if you're at the beginning of the line \s-1AND\s0 the end of the
line simultaneously.  The deeper underlying truth is that juxtaposition in
regular expressions always means \s-1AND\s0, except when you write an explicit \s-1OR\s0
using the vertical bar.  \f(CW\*(C`/ab/\*(C'\fR means match \*(L"a\*(R" \s-1AND\s0 (then) match \*(L"b\*(R",
although the attempted matches are made at different positions because \*(L"a\*(R"
is not a zero-width assertion, but a one-width assertion.
.PP
\&\fB\s-1WARNING\s0\fR: particularly complicated regular expressions can take
exponential time to solve because of the immense number of possible
ways they can use backtracking to try match.  For example, without
internal optimizations done by the regular expression engine, this will
take a painfully long time to run:
.PP
.Vb 1
\&    'aaaaaaaaaaaa' =~ /((a{0,5}){0,5})*[c]/
.Ve
.PP
And if you used \f(CW\*(C`*\*(C'\fR's in the internal groups instead of limiting them
to 0 through 5 matches, then it would take forever\*(--or until you ran
out of stack space.  Moreover, these internal optimizations are not
always applicable.  For example, if you put \f(CW\*(C`{0,5}\*(C'\fR instead of \f(CW\*(C`*\*(C'\fR
on the external group, no current optimization is applicable, and the
match takes a long time to finish.
.PP
A powerful tool for optimizing such beasts is what is known as an
\&\*(L"independent group\*(R",
which does not backtrack (see "\f(CW\*(C`(?>pattern)\*(C'\fR").  Note also that
zero-length look\-ahead/look\-behind assertions will not backtrack to make
the tail match, since they are in \*(L"logical\*(R" context: only 
whether they match is considered relevant.  For an example
where side-effects of look-ahead \fImight\fR have influenced the
following match, see "\f(CW\*(C`(?>pattern)\*(C'\fR".
.Sh "Version 8 Regular Expressions"
.IX Subsection "Version 8 Regular Expressions"
In case you're not familiar with the \*(L"regular\*(R" Version 8 regex
routines, here are the pattern-matching rules not described above.
.PP
Any single character matches itself, unless it is a \fImetacharacter\fR
with a special meaning described here or above.  You can cause
characters that normally function as metacharacters to be interpreted
literally by prefixing them with a \*(L"\e\*(R" (e.g., \*(L"\e.\*(R" matches a \*(L".\*(R", not any
character; \*(L"\e\e\*(R" matches a \*(L"\e\*(R").  A series of characters matches that
series of characters in the target string, so the pattern \f(CW\*(C`blurfl\*(C'\fR
would match \*(L"blurfl\*(R" in the target string.
.PP
You can specify a character class, by enclosing a list of characters
in \f(CW\*(C`[]\*(C'\fR, which will match any one character from the list.  If the
first character after the \*(L"[\*(R" is \*(L"^\*(R", the class matches any character not
in the list.  Within a list, the \*(L"\-\*(R" character specifies a
range, so that \f(CW\*(C`a\-z\*(C'\fR represents all characters between \*(L"a\*(R" and \*(L"z\*(R",
inclusive.  If you want either \*(L"\-\*(R" or \*(L"]\*(R" itself to be a member of a
class, put it at the start of the list (possibly after a \*(L"^\*(R"), or
escape it with a backslash.  \*(L"\-\*(R" is also taken literally when it is
at the end of the list, just before the closing \*(L"]\*(R".  (The
following all specify the same class of three characters: \f(CW\*(C`[\-az]\*(C'\fR,
\&\f(CW\*(C`[az\-]\*(C'\fR, and \f(CW\*(C`[a\e\-z]\*(C'\fR.  All are different from \f(CW\*(C`[a\-z]\*(C'\fR, which
specifies a class containing twenty-six characters, even on \s-1EBCDIC\s0
based coded character sets.)  Also, if you try to use the character 
classes \f(CW\*(C`\ew\*(C'\fR, \f(CW\*(C`\eW\*(C'\fR, \f(CW\*(C`\es\*(C'\fR, \f(CW\*(C`\eS\*(C'\fR, \f(CW\*(C`\ed\*(C'\fR, or \f(CW\*(C`\eD\*(C'\fR as endpoints of 
a range, that's not a range, the \*(L"\-\*(R" is understood literally.
.PP
Note also that the whole range idea is rather unportable between
character sets\*(--and even within character sets they may cause results
you probably didn't expect.  A sound principle is to use only ranges
that begin from and end at either alphabets of equal case ([a\-e],
[A\-E]), or digits ([0\-9]).  Anything else is unsafe.  If in doubt,
spell out the character sets in full.
.PP
Characters may be specified using a metacharacter syntax much like that
used in C: \*(L"\en\*(R" matches a newline, \*(L"\et\*(R" a tab, \*(L"\er\*(R" a carriage return,
\&\*(L"\ef\*(R" a form feed, etc.  More generally, \e\fInnn\fR, where \fInnn\fR is a string
of octal digits, matches the character whose coded character set value 
is \fInnn\fR.  Similarly, \ex\fInn\fR, where \fInn\fR are hexadecimal digits, 
matches the character whose numeric value is \fInn\fR. The expression \ec\fIx\fR 
matches the character control\-\fIx\fR.  Finally, the \*(L".\*(R" metacharacter 
matches any character except \*(L"\en\*(R" (unless you use \f(CW\*(C`/s\*(C'\fR).
.PP
You can specify a series of alternatives for a pattern using \*(L"|\*(R" to
separate them, so that \f(CW\*(C`fee|fie|foe\*(C'\fR will match any of \*(L"fee\*(R", \*(L"fie\*(R",
or \*(L"foe\*(R" in the target string (as would \f(CW\*(C`f(e|i|o)e\*(C'\fR).  The
first alternative includes everything from the last pattern delimiter
(\*(L"(\*(R", \*(L"[\*(R", or the beginning of the pattern) up to the first \*(L"|\*(R", and
the last alternative contains everything from the last \*(L"|\*(R" to the next
pattern delimiter.  That's why it's common practice to include
alternatives in parentheses: to minimize confusion about where they
start and end.
.PP
Alternatives are tried from left to right, so the first
alternative found for which the entire expression matches, is the one that
is chosen. This means that alternatives are not necessarily greedy. For
example: when matching \f(CW\*(C`foo|foot\*(C'\fR against \*(L"barefoot\*(R", only the \*(L"foo\*(R"
part will match, as that is the first alternative tried, and it successfully
matches the target string. (This might not seem important, but it is
important when you are capturing matched text using parentheses.)
.PP
Also remember that \*(L"|\*(R" is interpreted as a literal within square brackets,
so if you write \f(CW\*(C`[fee|fie|foe]\*(C'\fR you're really only matching \f(CW\*(C`[feio|]\*(C'\fR.
.PP
Within a pattern, you may designate subpatterns for later reference
by enclosing them in parentheses, and you may refer back to the
\&\fIn\fRth subpattern later in the pattern using the metacharacter
\&\e\fIn\fR.  Subpatterns are numbered based on the left to right order
of their opening parenthesis.  A backreference matches whatever
actually matched the subpattern in the string being examined, not
the rules for that subpattern.  Therefore, \f(CW\*(C`(0|0x)\ed*\es\e1\ed*\*(C'\fR will
match \*(L"0x1234 0x4321\*(R", but not \*(L"0x1234 01234\*(R", because subpattern
1 matched \*(L"0x\*(R", even though the rule \f(CW\*(C`0|0x\*(C'\fR could potentially match
the leading 0 in the second number.
.ie n .Sh "Warning on \e1 vs $1"
.el .Sh "Warning on \e1 vs \f(CW$1\fP"
.IX Subsection "Warning on 1 vs $1"
Some people get too used to writing things like:
.PP
.Vb 1
\&    $pattern =~ s/(\eW)/\e\e\e1/g;
.Ve
.PP
This is grandfathered for the \s-1RHS\s0 of a substitute to avoid shocking the
\&\fBsed\fR addicts, but it's a dirty habit to get into.  That's because in
PerlThink, the righthand side of an \f(CW\*(C`s///\*(C'\fR is a double-quoted string.  \f(CW\*(C`\e1\*(C'\fR in
the usual double-quoted string means a control\-A.  The customary Unix
meaning of \f(CW\*(C`\e1\*(C'\fR is kludged in for \f(CW\*(C`s///\*(C'\fR.  However, if you get into the habit
of doing that, you get yourself into trouble if you then add an \f(CW\*(C`/e\*(C'\fR
modifier.
.PP
.Vb 1
\&    s/(\ed+)/ \e1 + 1 /eg;        # causes warning under -w
.Ve
.PP
Or if you try to do
.PP
.Vb 1
\&    s/(\ed+)/\e1000/;
.Ve
.PP
You can't disambiguate that by saying \f(CW\*(C`\e{1}000\*(C'\fR, whereas you can fix it with
\&\f(CW\*(C`${1}000\*(C'\fR.  The operation of interpolation should not be confused
with the operation of matching a backreference.  Certainly they mean two
different things on the \fIleft\fR side of the \f(CW\*(C`s///\*(C'\fR.
.Sh "Repeated patterns matching zero-length substring"
.IX Subsection "Repeated patterns matching zero-length substring"
\&\fB\s-1WARNING\s0\fR: Difficult material (and prose) ahead.  This section needs a rewrite.
.PP
Regular expressions provide a terse and powerful programming language.  As
with most other power tools, power comes together with the ability
to wreak havoc.
.PP
A common abuse of this power stems from the ability to make infinite
loops using regular expressions, with something as innocuous as:
.PP
.Vb 1
\&    'foo' =~ m{ ( o? )* }x;
.Ve
.PP
The \f(CW\*(C`o?\*(C'\fR can match at the beginning of \f(CW'foo'\fR, and since the position
in the string is not moved by the match, \f(CW\*(C`o?\*(C'\fR would match again and again
because of the \f(CW\*(C`*\*(C'\fR modifier.  Another common way to create a similar cycle
is with the looping modifier \f(CW\*(C`//g\*(C'\fR:
.PP
.Vb 1
\&    @matches = ( 'foo' =~ m{ o? }xg );
.Ve
.PP
or
.PP
.Vb 1
\&    print "match: <$&>\en" while 'foo' =~ m{ o? }xg;
.Ve
.PP
or the loop implied by \fIsplit()\fR.
.PP
However, long experience has shown that many programming tasks may
be significantly simplified by using repeated subexpressions that
may match zero-length substrings.  Here's a simple example being:
.PP
.Vb 2
\&    @chars = split //, $string;           # // is not magic in split
\&    ($whitewashed = $string) =~ s/()/ /g; # parens avoid magic s// /
.Ve
.PP
Thus Perl allows such constructs, by \fIforcefully breaking
the infinite loop\fR.  The rules for this are different for lower-level
loops given by the greedy modifiers \f(CW\*(C`*+{}\*(C'\fR, and for higher-level
ones like the \f(CW\*(C`/g\*(C'\fR modifier or \fIsplit()\fR operator.
.PP
The lower-level loops are \fIinterrupted\fR (that is, the loop is
broken) when Perl detects that a repeated expression matched a
zero-length substring.   Thus
.PP
.Vb 1
\&   m{ (?: NON_ZERO_LENGTH | ZERO_LENGTH )* }x;
.Ve
.PP
is made equivalent to 
.PP
.Vb 4
\&   m{   (?: NON_ZERO_LENGTH )* 
\&      | 
\&        (?: ZERO_LENGTH )? 
\&    }x;
.Ve
.PP
The higher level-loops preserve an additional state between iterations:
whether the last match was zero\-length.  To break the loop, the following 
match after a zero-length match is prohibited to have a length of zero.
This prohibition interacts with backtracking (see \*(L"Backtracking\*(R"), 
and so the \fIsecond best\fR match is chosen if the \fIbest\fR match is of
zero length.
.PP
For example:
.PP
.Vb 2
\&    $_ = 'bar';
\&    s/\ew??/<$&>/g;
.Ve
.PP
results in \f(CW\*(C`<><b><><a><><r><>\*(C'\fR.  At each position of the string the best
match given by non-greedy \f(CW\*(C`??\*(C'\fR is the zero-length match, and the \fIsecond 
best\fR match is what is matched by \f(CW\*(C`\ew\*(C'\fR.  Thus zero-length matches
alternate with one-character-long matches.
.PP
Similarly, for repeated \f(CW\*(C`m/()/g\*(C'\fR the second-best match is the match at the 
position one notch further in the string.
.PP
The additional state of being \fImatched with zero-length\fR is associated with
the matched string, and is reset by each assignment to \fIpos()\fR.
Zero-length matches at the end of the previous match are ignored
during \f(CW\*(C`split\*(C'\fR.
.Sh "Combining pieces together"
.IX Subsection "Combining pieces together"
Each of the elementary pieces of regular expressions which were described
before (such as \f(CW\*(C`ab\*(C'\fR or \f(CW\*(C`\eZ\*(C'\fR) could match at most one substring
at the given position of the input string.  However, in a typical regular
expression these elementary pieces are combined into more complicated
patterns using combining operators \f(CW\*(C`ST\*(C'\fR, \f(CW\*(C`S|T\*(C'\fR, \f(CW\*(C`S*\*(C'\fR etc
(in these examples \f(CW\*(C`S\*(C'\fR and \f(CW\*(C`T\*(C'\fR are regular subexpressions).
.PP
Such combinations can include alternatives, leading to a problem of choice:
if we match a regular expression \f(CW\*(C`a|ab\*(C'\fR against \f(CW"abc"\fR, will it match
substring \f(CW"a"\fR or \f(CW"ab"\fR?  One way to describe which substring is
actually matched is the concept of backtracking (see \*(L"Backtracking\*(R").
However, this description is too low-level and makes you think
in terms of a particular implementation.
.PP
Another description starts with notions of \*(L"better\*(R"/\*(L"worse\*(R".  All the
substrings which may be matched by the given regular expression can be
sorted from the \*(L"best\*(R" match to the \*(L"worst\*(R" match, and it is the \*(L"best\*(R"
match which is chosen.  This substitutes the question of \*(L"what is chosen?\*(R"
by the question of \*(L"which matches are better, and which are worse?\*(R".
.PP
Again, for elementary pieces there is no such question, since at most
one match at a given position is possible.  This section describes the
notion of better/worse for combining operators.  In the description
below \f(CW\*(C`S\*(C'\fR and \f(CW\*(C`T\*(C'\fR are regular subexpressions.
.ie n .IP """ST""" 4
.el .IP "\f(CWST\fR" 4
.IX Item "ST"
Consider two possible matches, \f(CW\*(C`AB\*(C'\fR and \f(CW\*(C`A'B'\*(C'\fR, \f(CW\*(C`A\*(C'\fR and \f(CW\*(C`A'\*(C'\fR are
substrings which can be matched by \f(CW\*(C`S\*(C'\fR, \f(CW\*(C`B\*(C'\fR and \f(CW\*(C`B'\*(C'\fR are substrings
which can be matched by \f(CW\*(C`T\*(C'\fR. 
.Sp
If \f(CW\*(C`A\*(C'\fR is better match for \f(CW\*(C`S\*(C'\fR than \f(CW\*(C`A'\*(C'\fR, \f(CW\*(C`AB\*(C'\fR is a better
match than \f(CW\*(C`A'B'\*(C'\fR.
.Sp
If \f(CW\*(C`A\*(C'\fR and \f(CW\*(C`A'\*(C'\fR coincide: \f(CW\*(C`AB\*(C'\fR is a better match than \f(CW\*(C`AB'\*(C'\fR if
\&\f(CW\*(C`B\*(C'\fR is better match for \f(CW\*(C`T\*(C'\fR than \f(CW\*(C`B'\*(C'\fR.
.ie n .IP """S|T""" 4
.el .IP "\f(CWS|T\fR" 4
.IX Item "S|T"
When \f(CW\*(C`S\*(C'\fR can match, it is a better match than when only \f(CW\*(C`T\*(C'\fR can match.
.Sp
Ordering of two matches for \f(CW\*(C`S\*(C'\fR is the same as for \f(CW\*(C`S\*(C'\fR.  Similar for
two matches for \f(CW\*(C`T\*(C'\fR.
.ie n .IP """S{REPEAT_COUNT}""" 4
.el .IP "\f(CWS{REPEAT_COUNT}\fR" 4
.IX Item "S{REPEAT_COUNT}"
Matches as \f(CW\*(C`SSS...S\*(C'\fR (repeated as many times as necessary).
.ie n .IP """S{min,max}""" 4
.el .IP "\f(CWS{min,max}\fR" 4
.IX Item "S{min,max}"
Matches as \f(CW\*(C`S{max}|S{max\-1}|...|S{min+1}|S{min}\*(C'\fR.
.ie n .IP """S{min,max}?""" 4
.el .IP "\f(CWS{min,max}?\fR" 4
.IX Item "S{min,max}?"
Matches as \f(CW\*(C`S{min}|S{min+1}|...|S{max\-1}|S{max}\*(C'\fR.
.ie n .IP """S?""\fR, \f(CW""S*""\fR, \f(CW""S+""" 4
.el .IP "\f(CWS?\fR, \f(CWS*\fR, \f(CWS+\fR" 4
.IX Item "S?, S*, S+"
Same as \f(CW\*(C`S{0,1}\*(C'\fR, \f(CW\*(C`S{0,BIG_NUMBER}\*(C'\fR, \f(CW\*(C`S{1,BIG_NUMBER}\*(C'\fR respectively.
.ie n .IP """S??""\fR, \f(CW""S*?""\fR, \f(CW""S+?""" 4
.el .IP "\f(CWS??\fR, \f(CWS*?\fR, \f(CWS+?\fR" 4
.IX Item "S??, S*?, S+?"
Same as \f(CW\*(C`S{0,1}?\*(C'\fR, \f(CW\*(C`S{0,BIG_NUMBER}?\*(C'\fR, \f(CW\*(C`S{1,BIG_NUMBER}?\*(C'\fR respectively.
.ie n .IP """(?>S)""" 4
.el .IP "\f(CW(?>S)\fR" 4
.IX Item "(?>S)"
Matches the best match for \f(CW\*(C`S\*(C'\fR and only that.
.ie n .IP """(?=S)""\fR, \f(CW""(?<=S)""" 4
.el .IP "\f(CW(?=S)\fR, \f(CW(?<=S)\fR" 4
.IX Item "(?=S), (?<=S)"
Only the best match for \f(CW\*(C`S\*(C'\fR is considered.  (This is important only if
\&\f(CW\*(C`S\*(C'\fR has capturing parentheses, and backreferences are used somewhere
else in the whole regular expression.)
.ie n .IP """(?!S)""\fR, \f(CW""(?<!S)""" 4
.el .IP "\f(CW(?!S)\fR, \f(CW(?<!S)\fR" 4
.IX Item "(?!S), (?<!S)"
For this grouping operator there is no need to describe the ordering, since
only whether or not \f(CW\*(C`S\*(C'\fR can match is important.
.ie n .IP """(??{ EXPR })""" 4
.el .IP "\f(CW(??{ EXPR })\fR" 4
.IX Item "(??{ EXPR })"
The ordering is the same as for the regular expression which is
the result of \s-1EXPR\s0.
.ie n .IP """(?(condition)yes\-pattern|no\-pattern)""" 4
.el .IP "\f(CW(?(condition)yes\-pattern|no\-pattern)\fR" 4
.IX Item "(?(condition)yes-pattern|no-pattern)"
Recall that which of \f(CW\*(C`yes\-pattern\*(C'\fR or \f(CW\*(C`no\-pattern\*(C'\fR actually matches is
already determined.  The ordering of the matches is the same as for the
chosen subexpression.
.PP
The above recipes describe the ordering of matches \fIat a given position\fR.
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.
.Sh "Creating custom \s-1RE\s0 engines"
.IX Subsection "Creating custom RE engines"
Overloaded constants (see overload) provide a simple way to extend
the functionality of the \s-1RE\s0 engine.
.PP
Suppose that we want to enable a new \s-1RE\s0 escape-sequence \f(CW\*(C`\eY|\*(C'\fR which
matches at boundary between white-space characters and non-whitespace
characters.  Note that \f(CW\*(C`(?=\eS)(?<!\eS)|(?!\eS)(?<=\eS)\*(C'\fR matches exactly
at these positions, so we want to have each \f(CW\*(C`\eY|\*(C'\fR in the place of the
more complicated version.  We can create a module \f(CW\*(C`customre\*(C'\fR to do
this:
.PP
.Vb 2
\&    package customre;
\&    use overload;
.Ve
.PP
.Vb 5
\&    sub import {
\&      shift;
\&      die "No argument to customre::import allowed" if @_;
\&      overload::constant 'qr' => \e&convert;
\&    }
.Ve
.PP
.Vb 1
\&    sub invalid { die "/$_[0]/: invalid escape '\e\e$_[1]'"}
.Ve
.PP
.Vb 10
\&    my %rules = ( '\e\e' => '\e\e', 
\&                  'Y|' => qr/(?=\eS)(?<!\eS)|(?!\eS)(?<=\eS)/ );
\&    sub convert {
\&      my $re = shift;
\&      $re =~ s{ 
\&                \e\e ( \e\e | Y . )
\&              }
\&              { $rules{$1} or invalid($re,$1) }sgex; 
\&      return $re;
\&    }
.Ve
.PP
Now \f(CW\*(C`use customre\*(C'\fR enables the new escape in constant regular
expressions, i.e., those without any runtime variable interpolations.
As documented in overload, this conversion will work only over
literal parts of regular expressions.  For \f(CW\*(C`\eY|$re\eY|\*(C'\fR the variable
part of this regular expression needs to be converted explicitly
(but only if the special meaning of \f(CW\*(C`\eY|\*(C'\fR should be enabled inside \f(CW$re\fR):
.PP
.Vb 5
\&    use customre;
\&    $re = <>;
\&    chomp $re;
\&    $re = customre::convert $re;
\&    /\eY|$re\eY|/;
.Ve
.SH "BUGS"
.IX Header "BUGS"
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.
.PP
This document needs a rewrite that separates the tutorial content
from the reference content.
.SH "SEE ALSO"
.IX Header "SEE ALSO"
perlrequick.
.PP
perlretut.
.PP
\&\*(L"Regexp Quote-Like Operators\*(R" in perlop.
.PP
\&\*(L"Gory details of parsing quoted constructs\*(R" in perlop.
.PP
perlfaq6.
.PP
\&\*(L"pos\*(R" in perlfunc.
.PP
perllocale.
.PP
perlebcdic.
.PP
\&\fIMastering Regular Expressions\fR by Jeffrey Friedl, published
by O'Reilly and Associates.

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to [email protected].