1N/A=head1 NAME
1N/A
1N/Aperlre - Perl regular expressions
1N/A
1N/A=head1 DESCRIPTION
1N/A
1N/AThis page describes the syntax of regular expressions in Perl.
1N/A
1N/AIf you haven't used regular expressions before, a quick-start
1N/Aintroduction is available in L<perlrequick>, and a longer tutorial
1N/Aintroduction is available in L<perlretut>.
1N/A
1N/AFor reference on how regular expressions are used in matching
1N/Aoperations, plus various examples of the same, see discussions of
1N/AC<m//>, C<s///>, C<qr//> and C<??> in L<perlop/"Regexp Quote-Like
1N/AOperators">.
1N/A
1N/AMatching operations can have various modifiers. Modifiers
1N/Athat relate to the interpretation of the regular expression inside
1N/Aare listed below. Modifiers that alter the way a regular expression
1N/Ais used by Perl are detailed in L<perlop/"Regexp Quote-Like Operators"> and
1N/AL<perlop/"Gory details of parsing quoted constructs">.
1N/A
1N/A=over 4
1N/A
1N/A=item i
1N/A
1N/ADo case-insensitive pattern matching.
1N/A
1N/AIf C<use locale> is in effect, the case map is taken from the current
1N/Alocale. See L<perllocale>.
1N/A
1N/A=item m
1N/A
1N/ATreat string as multiple lines. That is, change "^" and "$" from matching
1N/Athe start or end of the string to matching the start or end of any
1N/Aline anywhere within the string.
1N/A
1N/A=item s
1N/A
1N/ATreat string as single line. That is, change "." to match any character
1N/Awhatsoever, even a newline, which normally it would not match.
1N/A
1N/AThe C</s> and C</m> modifiers both override the C<$*> setting. That
1N/Ais, no matter what C<$*> contains, C</s> without C</m> will force
1N/A"^" to match only at the beginning of the string and "$" to match
1N/Aonly at the end (or just before a newline at the end) of the string.
1N/ATogether, as /ms, they let the "." match any character whatsoever,
1N/Awhile still allowing "^" and "$" to match, respectively, just after
1N/Aand just before newlines within the string.
1N/A
1N/A=item x
1N/A
1N/AExtend your pattern's legibility by permitting whitespace and comments.
1N/A
1N/A=back
1N/A
1N/AThese are usually written as "the C</x> modifier", even though the delimiter
1N/Ain question might not really be a slash. Any of these
1N/Amodifiers may also be embedded within the regular expression itself using
1N/Athe C<(?...)> construct. See below.
1N/A
1N/AThe C</x> modifier itself needs a little more explanation. It tells
1N/Athe regular expression parser to ignore whitespace that is neither
1N/Abackslashed nor within a character class. You can use this to break up
1N/Ayour regular expression into (slightly) more readable parts. The C<#>
1N/Acharacter is also treated as a metacharacter introducing a comment,
1N/Ajust as in ordinary Perl code. This also means that if you want real
1N/Awhitespace or C<#> characters in the pattern (outside a character
1N/Aclass, where they are unaffected by C</x>), that you'll either have to
1N/Aescape them or encode them using octal or hex escapes. Taken together,
1N/Athese features go a long way towards making Perl's regular expressions
1N/Amore readable. Note that you have to be careful not to include the
1N/Apattern delimiter in the comment--perl has no way of knowing you did
1N/Anot intend to close the pattern early. See the C-comment deletion code
1N/Ain L<perlop>.
1N/A
1N/A=head2 Regular Expressions
1N/A
1N/AThe patterns used in Perl pattern matching derive from supplied in
1N/Athe Version 8 regex routines. (The routines are derived
1N/A(distantly) from Henry Spencer's freely redistributable reimplementation
1N/Aof the V8 routines.) See L<Version 8 Regular Expressions> for
1N/Adetails.
1N/A
1N/AIn particular the following metacharacters have their standard I<egrep>-ish
1N/Ameanings:
1N/A
1N/A \ Quote the next metacharacter
1N/A ^ Match the beginning of the line
1N/A . Match any character (except newline)
1N/A $ Match the end of the line (or before newline at the end)
1N/A | Alternation
1N/A () Grouping
1N/A [] Character class
1N/A
1N/ABy default, the "^" character is guaranteed to match only the
1N/Abeginning of the string, the "$" character only the end (or before the
1N/Anewline at the end), and Perl does certain optimizations with the
1N/Aassumption that the string contains only one line. Embedded newlines
1N/Awill not be matched by "^" or "$". You may, however, wish to treat a
1N/Astring as a multi-line buffer, such that the "^" will match after any
1N/Anewline within the string, and "$" will match before any newline. At the
1N/Acost of a little more overhead, you can do this by using the /m modifier
1N/Aon the pattern match operator. (Older programs did this by setting C<$*>,
1N/Abut this practice is now deprecated.)
1N/A
1N/ATo simplify multi-line substitutions, the "." character never matches a
1N/Anewline unless you use the C</s> modifier, which in effect tells Perl to pretend
1N/Athe string is a single line--even if it isn't. The C</s> modifier also
1N/Aoverrides the setting of C<$*>, in case you have some (badly behaved) older
1N/Acode that sets it in another module.
1N/A
1N/AThe following standard quantifiers are recognized:
1N/A
1N/A * Match 0 or more times
1N/A + Match 1 or more times
1N/A ? Match 1 or 0 times
1N/A {n} Match exactly n times
1N/A {n,} Match at least n times
1N/A {n,m} Match at least n but not more than m times
1N/A
1N/A(If a curly bracket occurs in any other context, it is treated
1N/Aas a regular character. In particular, the lower bound
1N/Ais not optional.) The "*" modifier is equivalent to C<{0,}>, the "+"
1N/Amodifier to C<{1,}>, and the "?" modifier to C<{0,1}>. n and m are limited
1N/Ato integral values less than a preset limit defined when perl is built.
1N/AThis is usually 32766 on the most common platforms. The actual limit can
1N/Abe seen in the error message generated by code such as this:
1N/A
1N/A $_ **= $_ , / {$_} / for 2 .. 42;
1N/A
1N/ABy default, a quantified subpattern is "greedy", that is, it will match as
1N/Amany times as possible (given a particular starting location) while still
1N/Aallowing the rest of the pattern to match. If you want it to match the
1N/Aminimum number of times possible, follow the quantifier with a "?". Note
1N/Athat the meanings don't change, just the "greediness":
1N/A
1N/A *? Match 0 or more times
1N/A +? Match 1 or more times
1N/A ?? Match 0 or 1 time
1N/A {n}? Match exactly n times
1N/A {n,}? Match at least n times
1N/A {n,m}? Match at least n but not more than m times
1N/A
1N/ABecause patterns are processed as double quoted strings, the following
1N/Aalso work:
1N/A
1N/A \t tab (HT, TAB)
1N/A \n newline (LF, NL)
1N/A \r return (CR)
1N/A \f form feed (FF)
1N/A \a alarm (bell) (BEL)
1N/A \e escape (think troff) (ESC)
1N/A \033 octal char (think of a PDP-11)
1N/A \x1B hex char
1N/A \x{263a} wide hex char (Unicode SMILEY)
1N/A \c[ control char
1N/A \N{name} named char
1N/A \l lowercase next char (think vi)
1N/A \u uppercase next char (think vi)
1N/A \L lowercase till \E (think vi)
1N/A \U uppercase till \E (think vi)
1N/A \E end case modification (think vi)
1N/A \Q quote (disable) pattern metacharacters till \E
1N/A
1N/AIf C<use locale> is in effect, the case map used by C<\l>, C<\L>, C<\u>
1N/Aand C<\U> is taken from the current locale. See L<perllocale>. For
1N/Adocumentation of C<\N{name}>, see L<charnames>.
1N/A
1N/AYou cannot include a literal C<$> or C<@> within a C<\Q> sequence.
1N/AAn unescaped C<$> or C<@> interpolates the corresponding variable,
1N/Awhile escaping will cause the literal string C<\$> to be matched.
1N/AYou'll need to write something like C<m/\Quser\E\@\Qhost/>.
1N/A
1N/AIn addition, Perl defines the following:
1N/A
1N/A \w Match a "word" character (alphanumeric plus "_")
1N/A \W Match a non-"word" character
1N/A \s Match a whitespace character
1N/A \S Match a non-whitespace character
1N/A \d Match a digit character
1N/A \D Match a non-digit character
1N/A \pP Match P, named property. Use \p{Prop} for longer names.
1N/A \PP Match non-P
1N/A \X Match eXtended Unicode "combining character sequence",
1N/A equivalent to (?:\PM\pM*)
1N/A \C Match a single C char (octet) even under Unicode.
1N/A NOTE: breaks up characters into their UTF-8 bytes,
1N/A so you may end up with malformed pieces of UTF-8.
1N/A Unsupported in lookbehind.
1N/A
1N/AA C<\w> matches a single alphanumeric character (an alphabetic
1N/Acharacter, or a decimal digit) or C<_>, not a whole word. Use C<\w+>
1N/Ato match a string of Perl-identifier characters (which isn't the same
1N/Aas matching an English word). If C<use locale> is in effect, the list
1N/Aof alphabetic characters generated by C<\w> is taken from the current
1N/Alocale. See L<perllocale>. You may use C<\w>, C<\W>, C<\s>, C<\S>,
1N/AC<\d>, and C<\D> within character classes, but if you try to use them
1N/Aas endpoints of a range, that's not a range, the "-" is understood
1N/Aliterally. If Unicode is in effect, C<\s> matches also "\x{85}",
1N/A"\x{2028}, and "\x{2029}", see L<perlunicode> for more details about
1N/AC<\pP>, C<\PP>, and C<\X>, and L<perluniintro> about Unicode in general.
1N/AYou can define your own C<\p> and C<\P> propreties, see L<perlunicode>.
1N/A
1N/AThe POSIX character class syntax
1N/A
1N/A [:class:]
1N/A
1N/Ais also available. The available classes and their backslash
1N/Aequivalents (if available) are as follows:
1N/A
1N/A alpha
1N/A alnum
1N/A ascii
1N/A blank [1]
1N/A cntrl
1N/A digit \d
1N/A graph
1N/A lower
1N/A print
1N/A punct
1N/A space \s [2]
1N/A upper
1N/A word \w [3]
1N/A xdigit
1N/A
1N/A=over
1N/A
1N/A=item [1]
1N/A
1N/AA GNU extension equivalent to C<[ \t]>, `all horizontal whitespace'.
1N/A
1N/A=item [2]
1N/A
1N/ANot exactly equivalent to C<\s> since the C<[[:space:]]> includes
1N/Aalso the (very rare) `vertical tabulator', "\ck", chr(11).
1N/A
1N/A=item [3]
1N/A
1N/AA Perl extension, see above.
1N/A
1N/A=back
1N/A
1N/AFor example use C<[:upper:]> to match all the uppercase characters.
1N/ANote that the C<[]> are part of the C<[::]> construct, not part of the
1N/Awhole character class. For example:
1N/A
1N/A [01[:alpha:]%]
1N/A
1N/Amatches zero, one, any alphabetic character, and the percentage sign.
1N/A
1N/AThe following equivalences to Unicode \p{} constructs and equivalent
1N/Abackslash character classes (if available), will hold:
1N/A
1N/A [:...:] \p{...} backslash
1N/A
1N/A alpha IsAlpha
1N/A alnum IsAlnum
1N/A ascii IsASCII
1N/A blank IsSpace
1N/A cntrl IsCntrl
1N/A digit IsDigit \d
1N/A graph IsGraph
1N/A lower IsLower
1N/A print IsPrint
1N/A punct IsPunct
1N/A space IsSpace
1N/A IsSpacePerl \s
1N/A upper IsUpper
1N/A word IsWord
1N/A xdigit IsXDigit
1N/A
1N/AFor example C<[:lower:]> and C<\p{IsLower}> are equivalent.
1N/A
1N/AIf the C<utf8> pragma is not used but the C<locale> pragma is, the
1N/Aclasses correlate with the usual isalpha(3) interface (except for
1N/A`word' and `blank').
1N/A
1N/AThe assumedly non-obviously named classes are:
1N/A
1N/A=over 4
1N/A
1N/A=item cntrl
1N/A
1N/AAny control character. Usually characters that don't produce output as
1N/Asuch but instead control the terminal somehow: for example newline and
1N/Abackspace are control characters. All characters with ord() less than
1N/A32 are most often classified as control characters (assuming ASCII,
1N/Athe ISO Latin character sets, and Unicode), as is the character with
1N/Athe ord() value of 127 (C<DEL>).
1N/A
1N/A=item graph
1N/A
1N/AAny alphanumeric or punctuation (special) character.
1N/A
1N/A=item print
1N/A
1N/AAny alphanumeric or punctuation (special) character or the space character.
1N/A
1N/A=item punct
1N/A
1N/AAny punctuation (special) character.
1N/A
1N/A=item xdigit
1N/A
1N/AAny hexadecimal digit. Though this may feel silly ([0-9A-Fa-f] would
1N/Awork just fine) it is included for completeness.
1N/A
1N/A=back
1N/A
1N/AYou can negate the [::] character classes by prefixing the class name
1N/Awith a '^'. This is a Perl extension. For example:
1N/A
1N/A POSIX traditional Unicode
1N/A
1N/A [:^digit:] \D \P{IsDigit}
1N/A [:^space:] \S \P{IsSpace}
1N/A [:^word:] \W \P{IsWord}
1N/A
1N/APerl respects the POSIX standard in that POSIX character classes are
1N/Aonly supported within a character class. The POSIX character classes
1N/A[.cc.] and [=cc=] are recognized but B<not> supported and trying to
1N/Ause them will cause an error.
1N/A
1N/APerl defines the following zero-width assertions:
1N/A
1N/A \b Match a word boundary
1N/A \B Match a non-(word boundary)
1N/A \A Match only at beginning of string
1N/A \Z Match only at end of string, or before newline at the end
1N/A \z Match only at end of string
1N/A \G Match only at pos() (e.g. at the end-of-match position
1N/A of prior m//g)
1N/A
1N/AA word boundary (C<\b>) is a spot between two characters
1N/Athat has a C<\w> on one side of it and a C<\W> on the other side
1N/Aof it (in either order), counting the imaginary characters off the
1N/Abeginning and end of the string as matching a C<\W>. (Within
1N/Acharacter classes C<\b> represents backspace rather than a word
1N/Aboundary, just as it normally does in any double-quoted string.)
1N/AThe C<\A> and C<\Z> are just like "^" and "$", except that they
1N/Awon't match multiple times when the C</m> modifier is used, while
1N/A"^" and "$" will match at every internal line boundary. To match
1N/Athe actual end of the string and not ignore an optional trailing
1N/Anewline, use C<\z>.
1N/A
1N/AThe C<\G> assertion can be used to chain global matches (using
1N/AC<m//g>), as described in L<perlop/"Regexp Quote-Like Operators">.
1N/AIt is also useful when writing C<lex>-like scanners, when you have
1N/Aseveral patterns that you want to match against consequent substrings
1N/Aof your string, see the previous reference. The actual location
1N/Awhere C<\G> will match can also be influenced by using C<pos()> as
1N/Aan lvalue: see L<perlfunc/pos>. Currently C<\G> is only fully
1N/Asupported when anchored to the start of the pattern; while it
1N/Ais permitted to use it elsewhere, as in C</(?<=\G..)./g>, some
1N/Asuch uses (C</.\G/g>, for example) currently cause problems, and
1N/Ait is recommended that you avoid such usage for now.
1N/A
1N/AThe bracketing construct C<( ... )> creates capture buffers. To
1N/Arefer to the digit'th buffer use \<digit> within the
1N/Amatch. Outside the match use "$" instead of "\". (The
1N/A\<digit> notation works in certain circumstances outside
1N/Athe match. See the warning below about \1 vs $1 for details.)
1N/AReferring back to another part of the match is called a
1N/AI<backreference>.
1N/A
1N/AThere is no limit to the number of captured substrings that you may
1N/Ause. However Perl also uses \10, \11, etc. as aliases for \010,
1N/A\011, etc. (Recall that 0 means octal, so \011 is the character at
1N/Anumber 9 in your coded character set; which would be the 10th character,
1N/Aa horizontal tab under ASCII.) Perl resolves this
1N/Aambiguity by interpreting \10 as a backreference only if at least 10
1N/Aleft parentheses have opened before it. Likewise \11 is a
1N/Abackreference only if at least 11 left parentheses have opened
1N/Abefore it. And so on. \1 through \9 are always interpreted as
1N/Abackreferences.
1N/A
1N/AExamples:
1N/A
1N/A s/^([^ ]*) *([^ ]*)/$2 $1/; # swap first two words
1N/A
1N/A if (/(.)\1/) { # find first doubled char
1N/A print "'$1' is the first doubled character\n";
1N/A }
1N/A
1N/A if (/Time: (..):(..):(..)/) { # parse out values
1N/A $hours = $1;
1N/A $minutes = $2;
1N/A $seconds = $3;
1N/A }
1N/A
1N/ASeveral special variables also refer back to portions of the previous
1N/Amatch. C<$+> returns whatever the last bracket match matched.
1N/AC<$&> returns the entire matched string. (At one point C<$0> did
1N/Aalso, but now it returns the name of the program.) C<$`> returns
1N/Aeverything before the matched string. C<$'> returns everything
1N/Aafter the matched string. And C<$^N> contains whatever was matched by
1N/Athe most-recently closed group (submatch). C<$^N> can be used in
1N/Aextended patterns (see below), for example to assign a submatch to a
1N/Avariable.
1N/A
1N/AThe numbered match variables ($1, $2, $3, etc.) and the related punctuation
1N/Aset (C<$+>, C<$&>, C<$`>, C<$'>, and C<$^N>) are all dynamically scoped
1N/Auntil the end of the enclosing block or until the next successful
1N/Amatch, whichever comes first. (See L<perlsyn/"Compound Statements">.)
1N/A
1N/AB<NOTE>: failed matches in Perl do not reset the match variables,
1N/Awhich makes easier to write code that tests for a series of more
1N/Aspecific cases and remembers the best match.
1N/A
1N/AB<WARNING>: Once Perl sees that you need one of C<$&>, C<$`>, or
1N/AC<$'> anywhere in the program, it has to provide them for every
1N/Apattern match. This may substantially slow your program. Perl
1N/Auses the same mechanism to produce $1, $2, etc, so you also pay a
1N/Aprice for each pattern that contains capturing parentheses. (To
1N/Aavoid this cost while retaining the grouping behaviour, use the
1N/Aextended regular expression C<(?: ... )> instead.) But if you never
1N/Ause C<$&>, C<$`> or C<$'>, then patterns I<without> capturing
1N/Aparentheses will not be penalized. So avoid C<$&>, C<$'>, and C<$`>
1N/Aif you can, but if you can't (and some algorithms really appreciate
1N/Athem), once you've used them once, use them at will, because you've
1N/Aalready paid the price. As of 5.005, C<$&> is not so costly as the
1N/Aother two.
1N/A
1N/ABackslashed metacharacters in Perl are alphanumeric, such as C<\b>,
1N/AC<\w>, C<\n>. Unlike some other regular expression languages, there
1N/Aare no backslashed symbols that aren't alphanumeric. So anything
1N/Athat looks like \\, \(, \), \<, \>, \{, or \} is always
1N/Ainterpreted as a literal character, not a metacharacter. This was
1N/Aonce used in a common idiom to disable or quote the special meanings
1N/Aof regular expression metacharacters in a string that you want to
1N/Ause for a pattern. Simply quote all non-"word" characters:
1N/A
1N/A $pattern =~ s/(\W)/\\$1/g;
1N/A
1N/A(If C<use locale> is set, then this depends on the current locale.)
1N/AToday it is more common to use the quotemeta() function or the C<\Q>
1N/Ametaquoting escape sequence to disable all metacharacters' special
1N/Ameanings like this:
1N/A
1N/A /$unquoted\Q$quoted\E$unquoted/
1N/A
1N/ABeware that if you put literal backslashes (those not inside
1N/Ainterpolated variables) between C<\Q> and C<\E>, double-quotish
1N/Abackslash interpolation may lead to confusing results. If you
1N/AI<need> to use literal backslashes within C<\Q...\E>,
1N/Aconsult L<perlop/"Gory details of parsing quoted constructs">.
1N/A
1N/A=head2 Extended Patterns
1N/A
1N/APerl also defines a consistent extension syntax for features not
1N/Afound in standard tools like B<awk> and B<lex>. The syntax is a
1N/Apair of parentheses with a question mark as the first thing within
1N/Athe parentheses. The character after the question mark indicates
1N/Athe extension.
1N/A
1N/AThe stability of these extensions varies widely. Some have been
1N/Apart of the core language for many years. Others are experimental
1N/Aand may change without warning or be completely removed. Check
1N/Athe documentation on an individual feature to verify its current
1N/Astatus.
1N/A
1N/AA question mark was chosen for this and for the minimal-matching
1N/Aconstruct because 1) question marks are rare in older regular
1N/Aexpressions, and 2) whenever you see one, you should stop and
1N/A"question" exactly what is going on. That's psychology...
1N/A
1N/A=over 10
1N/A
1N/A=item C<(?#text)>
1N/A
1N/AA comment. The text is ignored. If the C</x> modifier enables
1N/Awhitespace formatting, a simple C<#> will suffice. Note that Perl closes
1N/Athe comment as soon as it sees a C<)>, so there is no way to put a literal
1N/AC<)> in the comment.
1N/A
1N/A=item C<(?imsx-imsx)>
1N/A
1N/AOne or more embedded pattern-match modifiers, to be turned on (or
1N/Aturned off, if preceded by C<->) for the remainder of the pattern or
1N/Athe remainder of the enclosing pattern group (if any). This is
1N/Aparticularly useful for dynamic patterns, such as those read in from a
1N/Aconfiguration file, read in as an argument, are specified in a table
1N/Asomewhere, etc. Consider the case that some of which want to be case
1N/Asensitive and some do not. The case insensitive ones need to include
1N/Amerely C<(?i)> at the front of the pattern. For example:
1N/A
1N/A $pattern = "foobar";
1N/A if ( /$pattern/i ) { }
1N/A
1N/A # more flexible:
1N/A
1N/A $pattern = "(?i)foobar";
1N/A if ( /$pattern/ ) { }
1N/A
1N/AThese modifiers are restored at the end of the enclosing group. For example,
1N/A
1N/A ( (?i) blah ) \s+ \1
1N/A
1N/Awill match a repeated (I<including the case>!) word C<blah> in any
1N/Acase, assuming C<x> modifier, and no C<i> modifier outside this
1N/Agroup.
1N/A
1N/A=item C<(?:pattern)>
1N/A
1N/A=item C<(?imsx-imsx:pattern)>
1N/A
1N/AThis is for clustering, not capturing; it groups subexpressions like
1N/A"()", but doesn't make backreferences as "()" does. So
1N/A
1N/A @fields = split(/\b(?:a|b|c)\b/)
1N/A
1N/Ais like
1N/A
1N/A @fields = split(/\b(a|b|c)\b/)
1N/A
1N/Abut doesn't spit out extra fields. It's also cheaper not to capture
1N/Acharacters if you don't need to.
1N/A
1N/AAny letters between C<?> and C<:> act as flags modifiers as with
1N/AC<(?imsx-imsx)>. For example,
1N/A
1N/A /(?s-i:more.*than).*million/i
1N/A
1N/Ais equivalent to the more verbose
1N/A
1N/A /(?:(?s-i)more.*than).*million/i
1N/A
1N/A=item C<(?=pattern)>
1N/A
1N/AA zero-width positive look-ahead assertion. For example, C</\w+(?=\t)/>
1N/Amatches a word followed by a tab, without including the tab in C<$&>.
1N/A
1N/A=item C<(?!pattern)>
1N/A
1N/AA zero-width negative look-ahead assertion. For example C</foo(?!bar)/>
1N/Amatches any occurrence of "foo" that isn't followed by "bar". Note
1N/Ahowever that look-ahead and look-behind are NOT the same thing. You cannot
1N/Ause this for look-behind.
1N/A
1N/AIf you are looking for a "bar" that isn't preceded by a "foo", C</(?!foo)bar/>
1N/Awill not do what you want. That's because the C<(?!foo)> is just saying that
1N/Athe next thing cannot be "foo"--and it's not, it's a "bar", so "foobar" will
1N/Amatch. You would have to do something like C</(?!foo)...bar/> for that. We
1N/Asay "like" because there's the case of your "bar" not having three characters
1N/Abefore it. You could cover that this way: C</(?:(?!foo)...|^.{0,2})bar/>.
1N/ASometimes it's still easier just to say:
1N/A
1N/A if (/bar/ && $` !~ /foo$/)
1N/A
1N/AFor look-behind see below.
1N/A
1N/A=item C<(?<=pattern)>
1N/A
1N/AA zero-width positive look-behind assertion. For example, C</(?<=\t)\w+/>
1N/Amatches a word that follows a tab, without including the tab in C<$&>.
1N/AWorks only for fixed-width look-behind.
1N/A
1N/A=item C<(?<!pattern)>
1N/A
1N/AA zero-width negative look-behind assertion. For example C</(?<!bar)foo/>
1N/Amatches any occurrence of "foo" that does not follow "bar". Works
1N/Aonly for fixed-width look-behind.
1N/A
1N/A=item C<(?{ code })>
1N/A
1N/AB<WARNING>: This extended regular expression feature is considered
1N/Ahighly experimental, and may be changed or deleted without notice.
1N/A
1N/AThis zero-width assertion evaluates any embedded Perl code. It
1N/Aalways succeeds, and its C<code> is not interpolated. Currently,
1N/Athe rules to determine where the C<code> ends are somewhat convoluted.
1N/A
1N/AThis feature can be used together with the special variable C<$^N> to
1N/Acapture the results of submatches in variables without having to keep
1N/Atrack of the number of nested parentheses. For example:
1N/A
1N/A $_ = "The brown fox jumps over the lazy dog";
1N/A /the (\S+)(?{ $color = $^N }) (\S+)(?{ $animal = $^N })/i;
1N/A print "color = $color, animal = $animal\n";
1N/A
1N/AInside the C<(?{...})> block, C<$_> refers to the string the regular
1N/Aexpression is matching against. You can also use C<pos()> to know what is
1N/Athe current position of matching withing this string.
1N/A
1N/AThe C<code> is properly scoped in the following sense: If the assertion
1N/Ais backtracked (compare L<"Backtracking">), all changes introduced after
1N/AC<local>ization are undone, so that
1N/A
1N/A $_ = 'a' x 8;
1N/A m<
1N/A (?{ $cnt = 0 }) # Initialize $cnt.
1N/A (
1N/A a
1N/A (?{
1N/A local $cnt = $cnt + 1; # Update $cnt, backtracking-safe.
1N/A })
1N/A )*
1N/A aaaa
1N/A (?{ $res = $cnt }) # On success copy to non-localized
1N/A # location.
1N/A >x;
1N/A
1N/Awill set C<$res = 4>. Note that after the match, $cnt returns to the globally
1N/Aintroduced value, because the scopes that restrict C<local> operators
1N/Aare unwound.
1N/A
1N/AThis assertion may be used as a C<(?(condition)yes-pattern|no-pattern)>
1N/Aswitch. If I<not> used in this way, the result of evaluation of
1N/AC<code> is put into the special variable C<$^R>. This happens
1N/Aimmediately, so C<$^R> can be used from other C<(?{ code })> assertions
1N/Ainside the same regular expression.
1N/A
1N/AThe assignment to C<$^R> above is properly localized, so the old
1N/Avalue of C<$^R> is restored if the assertion is backtracked; compare
1N/AL<"Backtracking">.
1N/A
1N/AFor reasons of security, this construct is forbidden if the regular
1N/Aexpression involves run-time interpolation of variables, unless the
1N/Aperilous C<use re 'eval'> pragma has been used (see L<re>), or the
1N/Avariables contain results of C<qr//> operator (see
1N/AL<perlop/"qr/STRING/imosx">).
1N/A
1N/AThis restriction is because of the wide-spread and remarkably convenient
1N/Acustom of using run-time determined strings as patterns. For example:
1N/A
1N/A $re = <>;
1N/A chomp $re;
1N/A $string =~ /$re/;
1N/A
1N/ABefore Perl knew how to execute interpolated code within a pattern,
1N/Athis operation was completely safe from a security point of view,
1N/Aalthough it could raise an exception from an illegal pattern. If
1N/Ayou turn on the C<use re 'eval'>, though, it is no longer secure,
1N/Aso you should only do so if you are also using taint checking.
1N/ABetter yet, use the carefully constrained evaluation within a Safe
1N/Acompartment. See L<perlsec> for details about both these mechanisms.
1N/A
1N/A=item C<(??{ code })>
1N/A
1N/AB<WARNING>: This extended regular expression feature is considered
1N/Ahighly experimental, and may be changed or deleted without notice.
1N/AA simplified version of the syntax may be introduced for commonly
1N/Aused idioms.
1N/A
1N/AThis is a "postponed" regular subexpression. The C<code> is evaluated
1N/Aat run time, at the moment this subexpression may match. The result
1N/Aof evaluation is considered as a regular expression and matched as
1N/Aif it were inserted instead of this construct.
1N/A
1N/AThe C<code> is not interpolated. As before, the rules to determine
1N/Awhere the C<code> ends are currently somewhat convoluted.
1N/A
1N/AThe following pattern matches a parenthesized group:
1N/A
1N/A $re = qr{
1N/A \(
1N/A (?:
1N/A (?> [^()]+ ) # Non-parens without backtracking
1N/A |
1N/A (??{ $re }) # Group with matching parens
1N/A )*
1N/A \)
1N/A }x;
1N/A
1N/A=item C<< (?>pattern) >>
1N/A
1N/AB<WARNING>: This extended regular expression feature is considered
1N/Ahighly experimental, and may be changed or deleted without notice.
1N/A
1N/AAn "independent" subexpression, one which matches the substring
1N/Athat a I<standalone> C<pattern> would match if anchored at the given
1N/Aposition, and it matches I<nothing other than this substring>. This
1N/Aconstruct is useful for optimizations of what would otherwise be
1N/A"eternal" matches, because it will not backtrack (see L<"Backtracking">).
1N/AIt may also be useful in places where the "grab all you can, and do not
1N/Agive anything back" semantic is desirable.
1N/A
1N/AFor example: C<< ^(?>a*)ab >> will never match, since C<< (?>a*) >>
1N/A(anchored at the beginning of string, as above) will match I<all>
1N/Acharacters C<a> at the beginning of string, leaving no C<a> for
1N/AC<ab> to match. In contrast, C<a*ab> will match the same as C<a+b>,
1N/Asince the match of the subgroup C<a*> is influenced by the following
1N/Agroup C<ab> (see L<"Backtracking">). In particular, C<a*> inside
1N/AC<a*ab> will match fewer characters than a standalone C<a*>, since
1N/Athis makes the tail match.
1N/A
1N/AAn effect similar to C<< (?>pattern) >> may be achieved by writing
1N/AC<(?=(pattern))\1>. This matches the same substring as a standalone
1N/AC<a+>, and the following C<\1> eats the matched string; it therefore
1N/Amakes a zero-length assertion into an analogue of C<< (?>...) >>.
1N/A(The difference between these two constructs is that the second one
1N/Auses a capturing group, thus shifting ordinals of backreferences
1N/Ain the rest of a regular expression.)
1N/A
1N/AConsider this pattern:
1N/A
1N/A m{ \(
1N/A (
1N/A [^()]+ # x+
1N/A |
1N/A \( [^()]* \)
1N/A )+
1N/A \)
1N/A }x
1N/A
1N/AThat will efficiently match a nonempty group with matching parentheses
1N/Atwo levels deep or less. However, if there is no such group, it
1N/Awill take virtually forever on a long string. That's because there
1N/Aare so many different ways to split a long string into several
1N/Asubstrings. This is what C<(.+)+> is doing, and C<(.+)+> is similar
1N/Ato a subpattern of the above pattern. Consider how the pattern
1N/Aabove detects no-match on C<((()aaaaaaaaaaaaaaaaaa> in several
1N/Aseconds, but that each extra letter doubles this time. This
1N/Aexponential performance will make it appear that your program has
1N/Ahung. However, a tiny change to this pattern
1N/A
1N/A m{ \(
1N/A (
1N/A (?> [^()]+ ) # change x+ above to (?> x+ )
1N/A |
1N/A \( [^()]* \)
1N/A )+
1N/A \)
1N/A }x
1N/A
1N/Awhich uses C<< (?>...) >> matches exactly when the one above does (verifying
1N/Athis yourself would be a productive exercise), but finishes in a fourth
1N/Athe time when used on a similar string with 1000000 C<a>s. Be aware,
1N/Ahowever, that this pattern currently triggers a warning message under
1N/Athe C<use warnings> pragma or B<-w> switch saying it
1N/AC<"matches null string many times in regex">.
1N/A
1N/AOn simple groups, such as the pattern C<< (?> [^()]+ ) >>, a comparable
1N/Aeffect may be achieved by negative look-ahead, as in C<[^()]+ (?! [^()] )>.
1N/AThis was only 4 times slower on a string with 1000000 C<a>s.
1N/A
1N/AThe "grab all you can, and do not give anything back" semantic is desirable
1N/Ain many situations where on the first sight a simple C<()*> looks like
1N/Athe correct solution. Suppose we parse text with comments being delimited
1N/Aby C<#> followed by some optional (horizontal) whitespace. Contrary to
1N/Aits appearance, C<#[ \t]*> I<is not> the correct subexpression to match
1N/Athe comment delimiter, because it may "give up" some whitespace if
1N/Athe remainder of the pattern can be made to match that way. The correct
1N/Aanswer is either one of these:
1N/A
1N/A (?>#[ \t]*)
1N/A #[ \t]*(?![ \t])
1N/A
1N/AFor example, to grab non-empty comments into $1, one should use either
1N/Aone of these:
1N/A
1N/A / (?> \# [ \t]* ) ( .+ ) /x;
1N/A / \# [ \t]* ( [^ \t] .* ) /x;
1N/A
1N/AWhich one you pick depends on which of these expressions better reflects
1N/Athe above specification of comments.
1N/A
1N/A=item C<(?(condition)yes-pattern|no-pattern)>
1N/A
1N/A=item C<(?(condition)yes-pattern)>
1N/A
1N/AB<WARNING>: This extended regular expression feature is considered
1N/Ahighly experimental, and may be changed or deleted without notice.
1N/A
1N/AConditional expression. C<(condition)> should be either an integer in
1N/Aparentheses (which is valid if the corresponding pair of parentheses
1N/Amatched), or look-ahead/look-behind/evaluate zero-width assertion.
1N/A
1N/AFor example:
1N/A
1N/A m{ ( \( )?
1N/A [^()]+
1N/A (?(1) \) )
1N/A }x
1N/A
1N/Amatches a chunk of non-parentheses, possibly included in parentheses
1N/Athemselves.
1N/A
1N/A=back
1N/A
1N/A=head2 Backtracking
1N/A
1N/ANOTE: This section presents an abstract approximation of regular
1N/Aexpression behavior. For a more rigorous (and complicated) view of
1N/Athe rules involved in selecting a match among possible alternatives,
1N/Asee L<Combining pieces together>.
1N/A
1N/AA fundamental feature of regular expression matching involves the
1N/Anotion called I<backtracking>, which is currently used (when needed)
1N/Aby all regular expression quantifiers, namely C<*>, C<*?>, C<+>,
1N/AC<+?>, C<{n,m}>, and C<{n,m}?>. Backtracking is often optimized
1N/Ainternally, but the general principle outlined here is valid.
1N/A
1N/AFor a regular expression to match, the I<entire> regular expression must
1N/Amatch, not just part of it. So if the beginning of a pattern containing a
1N/Aquantifier succeeds in a way that causes later parts in the pattern to
1N/Afail, the matching engine backs up and recalculates the beginning
1N/Apart--that's why it's called backtracking.
1N/A
1N/AHere is an example of backtracking: Let's say you want to find the
1N/Aword following "foo" in the string "Food is on the foo table.":
1N/A
1N/A $_ = "Food is on the foo table.";
1N/A if ( /\b(foo)\s+(\w+)/i ) {
1N/A print "$2 follows $1.\n";
1N/A }
1N/A
1N/AWhen the match runs, the first part of the regular expression (C<\b(foo)>)
1N/Afinds a possible match right at the beginning of the string, and loads up
1N/A$1 with "Foo". However, as soon as the matching engine sees that there's
1N/Ano whitespace following the "Foo" that it had saved in $1, it realizes its
1N/Amistake and starts over again one character after where it had the
1N/Atentative match. This time it goes all the way until the next occurrence
1N/Aof "foo". The complete regular expression matches this time, and you get
1N/Athe expected output of "table follows foo."
1N/A
1N/ASometimes minimal matching can help a lot. Imagine you'd like to match
1N/Aeverything between "foo" and "bar". Initially, you write something
1N/Alike this:
1N/A
1N/A $_ = "The food is under the bar in the barn.";
1N/A if ( /foo(.*)bar/ ) {
1N/A print "got <$1>\n";
1N/A }
1N/A
1N/AWhich perhaps unexpectedly yields:
1N/A
1N/A got <d is under the bar in the >
1N/A
1N/AThat's because C<.*> was greedy, so you get everything between the
1N/AI<first> "foo" and the I<last> "bar". Here it's more effective
1N/Ato use minimal matching to make sure you get the text between a "foo"
1N/Aand the first "bar" thereafter.
1N/A
1N/A if ( /foo(.*?)bar/ ) { print "got <$1>\n" }
1N/A got <d is under the >
1N/A
1N/AHere's another example: let's say you'd like to match a number at the end
1N/Aof a string, and you also want to keep the preceding part of the match.
1N/ASo you write this:
1N/A
1N/A $_ = "I have 2 numbers: 53147";
1N/A if ( /(.*)(\d*)/ ) { # Wrong!
1N/A print "Beginning is <$1>, number is <$2>.\n";
1N/A }
1N/A
1N/AThat won't work at all, because C<.*> was greedy and gobbled up the
1N/Awhole string. As C<\d*> can match on an empty string the complete
1N/Aregular expression matched successfully.
1N/A
1N/A Beginning is <I have 2 numbers: 53147>, number is <>.
1N/A
1N/AHere are some variants, most of which don't work:
1N/A
1N/A $_ = "I have 2 numbers: 53147";
1N/A @pats = qw{
1N/A (.*)(\d*)
1N/A (.*)(\d+)
1N/A (.*?)(\d*)
1N/A (.*?)(\d+)
1N/A (.*)(\d+)$
1N/A (.*?)(\d+)$
1N/A (.*)\b(\d+)$
1N/A (.*\D)(\d+)$
1N/A };
1N/A
1N/A for $pat (@pats) {
1N/A printf "%-12s ", $pat;
1N/A if ( /$pat/ ) {
1N/A print "<$1> <$2>\n";
1N/A } else {
1N/A print "FAIL\n";
1N/A }
1N/A }
1N/A
1N/AThat will print out:
1N/A
1N/A (.*)(\d*) <I have 2 numbers: 53147> <>
1N/A (.*)(\d+) <I have 2 numbers: 5314> <7>
1N/A (.*?)(\d*) <> <>
1N/A (.*?)(\d+) <I have > <2>
1N/A (.*)(\d+)$ <I have 2 numbers: 5314> <7>
1N/A (.*?)(\d+)$ <I have 2 numbers: > <53147>
1N/A (.*)\b(\d+)$ <I have 2 numbers: > <53147>
1N/A (.*\D)(\d+)$ <I have 2 numbers: > <53147>
1N/A
1N/AAs you see, this can be a bit tricky. It's important to realize that a
1N/Aregular expression is merely a set of assertions that gives a definition
1N/Aof success. There may be 0, 1, or several different ways that the
1N/Adefinition might succeed against a particular string. And if there are
1N/Amultiple ways it might succeed, you need to understand backtracking to
1N/Aknow which variety of success you will achieve.
1N/A
1N/AWhen using look-ahead assertions and negations, this can all get even
1N/Atrickier. Imagine you'd like to find a sequence of non-digits not
1N/Afollowed by "123". You might try to write that as
1N/A
1N/A $_ = "ABC123";
1N/A if ( /^\D*(?!123)/ ) { # Wrong!
1N/A print "Yup, no 123 in $_\n";
1N/A }
1N/A
1N/ABut that isn't going to match; at least, not the way you're hoping. It
1N/Aclaims that there is no 123 in the string. Here's a clearer picture of
1N/Awhy that pattern matches, contrary to popular expectations:
1N/A
1N/A $x = 'ABC123' ;
1N/A $y = 'ABC445' ;
1N/A
1N/A print "1: got $1\n" if $x =~ /^(ABC)(?!123)/ ;
1N/A print "2: got $1\n" if $y =~ /^(ABC)(?!123)/ ;
1N/A
1N/A print "3: got $1\n" if $x =~ /^(\D*)(?!123)/ ;
1N/A print "4: got $1\n" if $y =~ /^(\D*)(?!123)/ ;
1N/A
1N/AThis prints
1N/A
1N/A 2: got ABC
1N/A 3: got AB
1N/A 4: got ABC
1N/A
1N/AYou might have expected test 3 to fail because it seems to a more
1N/Ageneral purpose version of test 1. The important difference between
1N/Athem is that test 3 contains a quantifier (C<\D*>) and so can use
1N/Abacktracking, whereas test 1 will not. What's happening is
1N/Athat you've asked "Is it true that at the start of $x, following 0 or more
1N/Anon-digits, you have something that's not 123?" If the pattern matcher had
1N/Alet C<\D*> expand to "ABC", this would have caused the whole pattern to
1N/Afail.
1N/A
1N/AThe search engine will initially match C<\D*> with "ABC". Then it will
1N/Atry to match C<(?!123> with "123", which fails. But because
1N/Aa quantifier (C<\D*>) has been used in the regular expression, the
1N/Asearch engine can backtrack and retry the match differently
1N/Ain the hope of matching the complete regular expression.
1N/A
1N/AThe pattern really, I<really> wants to succeed, so it uses the
1N/Astandard pattern back-off-and-retry and lets C<\D*> expand to just "AB" this
1N/Atime. Now there's indeed something following "AB" that is not
1N/A"123". It's "C123", which suffices.
1N/A
1N/AWe can deal with this by using both an assertion and a negation.
1N/AWe'll say that the first part in $1 must be followed both by a digit
1N/Aand by something that's not "123". Remember that the look-aheads
1N/Aare zero-width expressions--they only look, but don't consume any
1N/Aof the string in their match. So rewriting this way produces what
1N/Ayou'd expect; that is, case 5 will fail, but case 6 succeeds:
1N/A
1N/A print "5: got $1\n" if $x =~ /^(\D*)(?=\d)(?!123)/ ;
1N/A print "6: got $1\n" if $y =~ /^(\D*)(?=\d)(?!123)/ ;
1N/A
1N/A 6: got ABC
1N/A
1N/AIn other words, the two zero-width assertions next to each other work as though
1N/Athey're ANDed together, just as you'd use any built-in assertions: C</^$/>
1N/Amatches only if you're at the beginning of the line AND the end of the
1N/Aline simultaneously. The deeper underlying truth is that juxtaposition in
1N/Aregular expressions always means AND, except when you write an explicit OR
1N/Ausing the vertical bar. C</ab/> means match "a" AND (then) match "b",
1N/Aalthough the attempted matches are made at different positions because "a"
1N/Ais not a zero-width assertion, but a one-width assertion.
1N/A
1N/AB<WARNING>: particularly complicated regular expressions can take
1N/Aexponential time to solve because of the immense number of possible
1N/Aways they can use backtracking to try match. For example, without
1N/Ainternal optimizations done by the regular expression engine, this will
1N/Atake a painfully long time to run:
1N/A
1N/A 'aaaaaaaaaaaa' =~ /((a{0,5}){0,5})*[c]/
1N/A
1N/AAnd if you used C<*>'s in the internal groups instead of limiting them
1N/Ato 0 through 5 matches, then it would take forever--or until you ran
1N/Aout of stack space. Moreover, these internal optimizations are not
1N/Aalways applicable. For example, if you put C<{0,5}> instead of C<*>
1N/Aon the external group, no current optimization is applicable, and the
1N/Amatch takes a long time to finish.
1N/A
1N/AA powerful tool for optimizing such beasts is what is known as an
1N/A"independent group",
1N/Awhich does not backtrack (see L<C<< (?>pattern) >>>). Note also that
1N/Azero-length look-ahead/look-behind assertions will not backtrack to make
1N/Athe tail match, since they are in "logical" context: only
1N/Awhether they match is considered relevant. For an example
1N/Awhere side-effects of look-ahead I<might> have influenced the
1N/Afollowing match, see L<C<< (?>pattern) >>>.
1N/A
1N/A=head2 Version 8 Regular Expressions
1N/A
1N/AIn case you're not familiar with the "regular" Version 8 regex
1N/Aroutines, here are the pattern-matching rules not described above.
1N/A
1N/AAny single character matches itself, unless it is a I<metacharacter>
1N/Awith a special meaning described here or above. You can cause
1N/Acharacters that normally function as metacharacters to be interpreted
1N/Aliterally by prefixing them with a "\" (e.g., "\." matches a ".", not any
1N/Acharacter; "\\" matches a "\"). A series of characters matches that
1N/Aseries of characters in the target string, so the pattern C<blurfl>
1N/Awould match "blurfl" in the target string.
1N/A
1N/AYou can specify a character class, by enclosing a list of characters
1N/Ain C<[]>, which will match any one character from the list. If the
1N/Afirst character after the "[" is "^", the class matches any character not
1N/Ain the list. Within a list, the "-" character specifies a
1N/Arange, so that C<a-z> represents all characters between "a" and "z",
1N/Ainclusive. If you want either "-" or "]" itself to be a member of a
1N/Aclass, put it at the start of the list (possibly after a "^"), or
1N/Aescape it with a backslash. "-" is also taken literally when it is
1N/Aat the end of the list, just before the closing "]". (The
1N/Afollowing all specify the same class of three characters: C<[-az]>,
1N/AC<[az-]>, and C<[a\-z]>. All are different from C<[a-z]>, which
1N/Aspecifies a class containing twenty-six characters, even on EBCDIC
1N/Abased coded character sets.) Also, if you try to use the character
1N/Aclasses C<\w>, C<\W>, C<\s>, C<\S>, C<\d>, or C<\D> as endpoints of
1N/Aa range, that's not a range, the "-" is understood literally.
1N/A
1N/ANote also that the whole range idea is rather unportable between
1N/Acharacter sets--and even within character sets they may cause results
1N/Ayou probably didn't expect. A sound principle is to use only ranges
1N/Athat begin from and end at either alphabets of equal case ([a-e],
1N/A[A-E]), or digits ([0-9]). Anything else is unsafe. If in doubt,
1N/Aspell out the character sets in full.
1N/A
1N/ACharacters may be specified using a metacharacter syntax much like that
1N/Aused in C: "\n" matches a newline, "\t" a tab, "\r" a carriage return,
1N/A"\f" a form feed, etc. More generally, \I<nnn>, where I<nnn> is a string
1N/Aof octal digits, matches the character whose coded character set value
1N/Ais I<nnn>. Similarly, \xI<nn>, where I<nn> are hexadecimal digits,
1N/Amatches the character whose numeric value is I<nn>. The expression \cI<x>
1N/Amatches the character control-I<x>. Finally, the "." metacharacter
1N/Amatches any character except "\n" (unless you use C</s>).
1N/A
1N/AYou can specify a series of alternatives for a pattern using "|" to
1N/Aseparate them, so that C<fee|fie|foe> will match any of "fee", "fie",
1N/Aor "foe" in the target string (as would C<f(e|i|o)e>). The
1N/Afirst alternative includes everything from the last pattern delimiter
1N/A("(", "[", or the beginning of the pattern) up to the first "|", and
1N/Athe last alternative contains everything from the last "|" to the next
1N/Apattern delimiter. That's why it's common practice to include
1N/Aalternatives in parentheses: to minimize confusion about where they
1N/Astart and end.
1N/A
1N/AAlternatives are tried from left to right, so the first
1N/Aalternative found for which the entire expression matches, is the one that
1N/Ais chosen. This means that alternatives are not necessarily greedy. For
1N/Aexample: when matching C<foo|foot> against "barefoot", only the "foo"
1N/Apart will match, as that is the first alternative tried, and it successfully
1N/Amatches the target string. (This might not seem important, but it is
1N/Aimportant when you are capturing matched text using parentheses.)
1N/A
1N/AAlso remember that "|" is interpreted as a literal within square brackets,
1N/Aso if you write C<[fee|fie|foe]> you're really only matching C<[feio|]>.
1N/A
1N/AWithin a pattern, you may designate subpatterns for later reference
1N/Aby enclosing them in parentheses, and you may refer back to the
1N/AI<n>th subpattern later in the pattern using the metacharacter
1N/A\I<n>. Subpatterns are numbered based on the left to right order
1N/Aof their opening parenthesis. A backreference matches whatever
1N/Aactually matched the subpattern in the string being examined, not
1N/Athe rules for that subpattern. Therefore, C<(0|0x)\d*\s\1\d*> will
1N/Amatch "0x1234 0x4321", but not "0x1234 01234", because subpattern
1N/A1 matched "0x", even though the rule C<0|0x> could potentially match
1N/Athe leading 0 in the second number.
1N/A
1N/A=head2 Warning on \1 vs $1
1N/A
1N/ASome people get too used to writing things like:
1N/A
1N/A $pattern =~ s/(\W)/\\\1/g;
1N/A
1N/AThis is grandfathered for the RHS of a substitute to avoid shocking the
1N/AB<sed> addicts, but it's a dirty habit to get into. That's because in
1N/APerlThink, the righthand side of an C<s///> is a double-quoted string. C<\1> in
1N/Athe usual double-quoted string means a control-A. The customary Unix
1N/Ameaning of C<\1> is kludged in for C<s///>. However, if you get into the habit
1N/Aof doing that, you get yourself into trouble if you then add an C</e>
1N/Amodifier.
1N/A
1N/A s/(\d+)/ \1 + 1 /eg; # causes warning under -w
1N/A
1N/AOr if you try to do
1N/A
1N/A s/(\d+)/\1000/;
1N/A
1N/AYou can't disambiguate that by saying C<\{1}000>, whereas you can fix it with
1N/AC<${1}000>. The operation of interpolation should not be confused
1N/Awith the operation of matching a backreference. Certainly they mean two
1N/Adifferent things on the I<left> side of the C<s///>.
1N/A
1N/A=head2 Repeated patterns matching zero-length substring
1N/A
1N/AB<WARNING>: Difficult material (and prose) ahead. This section needs a rewrite.
1N/A
1N/ARegular expressions provide a terse and powerful programming language. As
1N/Awith most other power tools, power comes together with the ability
1N/Ato wreak havoc.
1N/A
1N/AA common abuse of this power stems from the ability to make infinite
1N/Aloops using regular expressions, with something as innocuous as:
1N/A
1N/A 'foo' =~ m{ ( o? )* }x;
1N/A
1N/AThe C<o?> can match at the beginning of C<'foo'>, and since the position
1N/Ain the string is not moved by the match, C<o?> would match again and again
1N/Abecause of the C<*> modifier. Another common way to create a similar cycle
1N/Ais with the looping modifier C<//g>:
1N/A
1N/A @matches = ( 'foo' =~ m{ o? }xg );
1N/A
1N/Aor
1N/A
1N/A print "match: <$&>\n" while 'foo' =~ m{ o? }xg;
1N/A
1N/Aor the loop implied by split().
1N/A
1N/AHowever, long experience has shown that many programming tasks may
1N/Abe significantly simplified by using repeated subexpressions that
1N/Amay match zero-length substrings. Here's a simple example being:
1N/A
1N/A @chars = split //, $string; # // is not magic in split
1N/A ($whitewashed = $string) =~ s/()/ /g; # parens avoid magic s// /
1N/A
1N/AThus Perl allows such constructs, by I<forcefully breaking
1N/Athe infinite loop>. The rules for this are different for lower-level
1N/Aloops given by the greedy modifiers C<*+{}>, and for higher-level
1N/Aones like the C</g> modifier or split() operator.
1N/A
1N/AThe lower-level loops are I<interrupted> (that is, the loop is
1N/Abroken) when Perl detects that a repeated expression matched a
1N/Azero-length substring. Thus
1N/A
1N/A m{ (?: NON_ZERO_LENGTH | ZERO_LENGTH )* }x;
1N/A
1N/Ais made equivalent to
1N/A
1N/A m{ (?: NON_ZERO_LENGTH )*
1N/A |
1N/A (?: ZERO_LENGTH )?
1N/A }x;
1N/A
1N/AThe higher level-loops preserve an additional state between iterations:
1N/Awhether the last match was zero-length. To break the loop, the following
1N/Amatch after a zero-length match is prohibited to have a length of zero.
1N/AThis prohibition interacts with backtracking (see L<"Backtracking">),
1N/Aand so the I<second best> match is chosen if the I<best> match is of
1N/Azero length.
1N/A
1N/AFor example:
1N/A
1N/A $_ = 'bar';
1N/A s/\w??/<$&>/g;
1N/A
1N/Aresults in C<< <><b><><a><><r><> >>. At each position of the string the best
1N/Amatch given by non-greedy C<??> is the zero-length match, and the I<second
1N/Abest> match is what is matched by C<\w>. Thus zero-length matches
1N/Aalternate with one-character-long matches.
1N/A
1N/ASimilarly, for repeated C<m/()/g> the second-best match is the match at the
1N/Aposition one notch further in the string.
1N/A
1N/AThe additional state of being I<matched with zero-length> is associated with
1N/Athe matched string, and is reset by each assignment to pos().
1N/AZero-length matches at the end of the previous match are ignored
1N/Aduring C<split>.
1N/A
1N/A=head2 Combining pieces together
1N/A
1N/AEach of the elementary pieces of regular expressions which were described
1N/Abefore (such as C<ab> or C<\Z>) could match at most one substring
1N/Aat the given position of the input string. However, in a typical regular
1N/Aexpression these elementary pieces are combined into more complicated
1N/Apatterns using combining operators C<ST>, C<S|T>, C<S*> etc
1N/A(in these examples C<S> and C<T> are regular subexpressions).
1N/A
1N/ASuch combinations can include alternatives, leading to a problem of choice:
1N/Aif we match a regular expression C<a|ab> against C<"abc">, will it match
1N/Asubstring C<"a"> or C<"ab">? One way to describe which substring is
1N/Aactually matched is the concept of backtracking (see L<"Backtracking">).
1N/AHowever, this description is too low-level and makes you think
1N/Ain terms of a particular implementation.
1N/A
1N/AAnother description starts with notions of "better"/"worse". All the
1N/Asubstrings which may be matched by the given regular expression can be
1N/Asorted from the "best" match to the "worst" match, and it is the "best"
1N/Amatch which is chosen. This substitutes the question of "what is chosen?"
1N/Aby the question of "which matches are better, and which are worse?".
1N/A
1N/AAgain, for elementary pieces there is no such question, since at most
1N/Aone match at a given position is possible. This section describes the
1N/Anotion of better/worse for combining operators. In the description
1N/Abelow C<S> and C<T> are regular subexpressions.
1N/A
1N/A=over 4
1N/A
1N/A=item C<ST>
1N/A
1N/AConsider two possible matches, C<AB> and C<A'B'>, C<A> and C<A'> are
1N/Asubstrings which can be matched by C<S>, C<B> and C<B'> are substrings
1N/Awhich can be matched by C<T>.
1N/A
1N/AIf C<A> is better match for C<S> than C<A'>, C<AB> is a better
1N/Amatch than C<A'B'>.
1N/A
1N/AIf C<A> and C<A'> coincide: C<AB> is a better match than C<AB'> if
1N/AC<B> is better match for C<T> than C<B'>.
1N/A
1N/A=item C<S|T>
1N/A
1N/AWhen C<S> can match, it is a better match than when only C<T> can match.
1N/A
1N/AOrdering of two matches for C<S> is the same as for C<S>. Similar for
1N/Atwo matches for C<T>.
1N/A
1N/A=item C<S{REPEAT_COUNT}>
1N/A
1N/AMatches as C<SSS...S> (repeated as many times as necessary).
1N/A
1N/A=item C<S{min,max}>
1N/A
1N/AMatches as C<S{max}|S{max-1}|...|S{min+1}|S{min}>.
1N/A
1N/A=item C<S{min,max}?>
1N/A
1N/AMatches as C<S{min}|S{min+1}|...|S{max-1}|S{max}>.
1N/A
1N/A=item C<S?>, C<S*>, C<S+>
1N/A
1N/ASame as C<S{0,1}>, C<S{0,BIG_NUMBER}>, C<S{1,BIG_NUMBER}> respectively.
1N/A
1N/A=item C<S??>, C<S*?>, C<S+?>
1N/A
1N/ASame as C<S{0,1}?>, C<S{0,BIG_NUMBER}?>, C<S{1,BIG_NUMBER}?> respectively.
1N/A
1N/A=item C<< (?>S) >>
1N/A
1N/AMatches the best match for C<S> and only that.
1N/A
1N/A=item C<(?=S)>, C<(?<=S)>
1N/A
1N/AOnly the best match for C<S> is considered. (This is important only if
1N/AC<S> has capturing parentheses, and backreferences are used somewhere
1N/Aelse in the whole regular expression.)
1N/A
1N/A=item C<(?!S)>, C<(?<!S)>
1N/A
1N/AFor this grouping operator there is no need to describe the ordering, since
1N/Aonly whether or not C<S> can match is important.
1N/A
1N/A=item C<(??{ EXPR })>
1N/A
1N/AThe ordering is the same as for the regular expression which is
1N/Athe result of EXPR.
1N/A
1N/A=item C<(?(condition)yes-pattern|no-pattern)>
1N/A
1N/ARecall that which of C<yes-pattern> or C<no-pattern> actually matches is
1N/Aalready determined. The ordering of the matches is the same as for the
1N/Achosen subexpression.
1N/A
1N/A=back
1N/A
1N/AThe above recipes describe the ordering of matches I<at a given position>.
1N/AOne more rule is needed to understand how a match is determined for the
1N/Awhole regular expression: a match at an earlier position is always better
1N/Athan a match at a later position.
1N/A
1N/A=head2 Creating custom RE engines
1N/A
1N/AOverloaded constants (see L<overload>) provide a simple way to extend
1N/Athe functionality of the RE engine.
1N/A
1N/ASuppose that we want to enable a new RE escape-sequence C<\Y|> which
1N/Amatches at boundary between white-space characters and non-whitespace
1N/Acharacters. Note that C<(?=\S)(?<!\S)|(?!\S)(?<=\S)> matches exactly
1N/Aat these positions, so we want to have each C<\Y|> in the place of the
1N/Amore complicated version. We can create a module C<customre> to do
1N/Athis:
1N/A
1N/A package customre;
1N/A use overload;
1N/A
1N/A sub import {
1N/A shift;
1N/A die "No argument to customre::import allowed" if @_;
1N/A overload::constant 'qr' => \&convert;
1N/A }
1N/A
1N/A sub invalid { die "/$_[0]/: invalid escape '\\$_[1]'"}
1N/A
1N/A my %rules = ( '\\' => '\\',
1N/A 'Y|' => qr/(?=\S)(?<!\S)|(?!\S)(?<=\S)/ );
1N/A sub convert {
1N/A my $re = shift;
1N/A $re =~ s{
1N/A \\ ( \\ | Y . )
1N/A }
1N/A { $rules{$1} or invalid($re,$1) }sgex;
1N/A return $re;
1N/A }
1N/A
1N/ANow C<use customre> enables the new escape in constant regular
1N/Aexpressions, i.e., those without any runtime variable interpolations.
1N/AAs documented in L<overload>, this conversion will work only over
1N/Aliteral parts of regular expressions. For C<\Y|$re\Y|> the variable
1N/Apart of this regular expression needs to be converted explicitly
1N/A(but only if the special meaning of C<\Y|> should be enabled inside $re):
1N/A
1N/A use customre;
1N/A $re = <>;
1N/A chomp $re;
1N/A $re = customre::convert $re;
1N/A /\Y|$re\Y|/;
1N/A
1N/A=head1 BUGS
1N/A
1N/AThis document varies from difficult to understand to completely
1N/Aand utterly opaque. The wandering prose riddled with jargon is
1N/Ahard to fathom in several places.
1N/A
1N/AThis document needs a rewrite that separates the tutorial content
1N/Afrom the reference content.
1N/A
1N/A=head1 SEE ALSO
1N/A
1N/AL<perlrequick>.
1N/A
1N/AL<perlretut>.
1N/A
1N/AL<perlop/"Regexp Quote-Like Operators">.
1N/A
1N/AL<perlop/"Gory details of parsing quoted constructs">.
1N/A
1N/AL<perlfaq6>.
1N/A
1N/AL<perlfunc/pos>.
1N/A
1N/AL<perllocale>.
1N/A
1N/AL<perlebcdic>.
1N/A
1N/AI<Mastering Regular Expressions> by Jeffrey Friedl, published
1N/Aby O'Reilly and Associates.