home *** CD-ROM | disk | FTP | other *** search
/ Acorn User 10 / AU_CD10.iso / Updates / Perl / Non-RPC / Docs / perlre < prev    next >
Text File  |  1999-04-17  |  43KB  |  1,053 lines

  1. NAME
  2.     perlre - Perl regular expressions
  3.  
  4. DESCRIPTION
  5.     This page describes the syntax of regular expressions in Perl.
  6.     For a description of how to *use* regular expressions in
  7.     matching operations, plus various examples of the same, see
  8.     discussion of `m//', `s///', `qr//' and `??' in the section on
  9.     "Regexp Quote-Like Operators" in the perlop manpage.
  10.  
  11.     The matching operations can have various modifiers. The
  12.     modifiers that relate to the interpretation of the regular
  13.     expression inside are listed below. For the modifiers that alter
  14.     the way a regular expression is used by Perl, see the section on
  15.     "Regexp Quote-Like Operators" in the perlop manpage and the
  16.     section on "Gory details of parsing quoted constructs" in the
  17.     perlop manpage.
  18.  
  19.     i   Do case-insensitive pattern matching.
  20.  
  21.         If `use locale' is in effect, the case map is taken from the
  22.         current locale. See the perllocale manpage.
  23.  
  24.     m   Treat string as multiple lines. That is, change "^" and "$" from
  25.         matching at only the very start or end of the string to the
  26.         start or end of any line anywhere within the string,
  27.  
  28.     s   Treat string as single line. That is, change "." to match any
  29.         character whatsoever, even a newline, which it normally
  30.         would not match.
  31.  
  32.         The `/s' and `/m' modifiers both override the `$*' setting.
  33.         That is, no matter what `$*' contains, `/s' without `/m'
  34.         will force "^" to match only at the beginning of the string
  35.         and "$" to match only at the end (or just before a newline
  36.         at the end) of the string. Together, as /ms, they let the
  37.         "." match any character whatsoever, while yet allowing "^"
  38.         and "$" to match, respectively, just after and just before
  39.         newlines within the string.
  40.  
  41.     x   Extend your pattern's legibility by permitting whitespace and
  42.         comments.
  43.  
  44.  
  45.     These are usually written as "the `/x' modifier", even though
  46.     the delimiter in question might not actually be a slash. In
  47.     fact, any of these modifiers may also be embedded within the
  48.     regular expression itself using the new `(?...)' construct. See
  49.     below.
  50.  
  51.     The `/x' modifier itself needs a little more explanation. It
  52.     tells the regular expression parser to ignore whitespace that is
  53.     neither backslashed nor within a character class. You can use
  54.     this to break up your regular expression into (slightly) more
  55.     readable parts. The `#' character is also treated as a
  56.     metacharacter introducing a comment, just as in ordinary Perl
  57.     code. This also means that if you want real whitespace or `#'
  58.     characters in the pattern (outside of a character class, where
  59.     they are unaffected by `/x'), that you'll either have to escape
  60.     them or encode them using octal or hex escapes. Taken together,
  61.     these features go a long way towards making Perl's regular
  62.     expressions more readable. Note that you have to be careful not
  63.     to include the pattern delimiter in the comment--perl has no way
  64.     of knowing you did not intend to close the pattern early. See
  65.     the C-comment deletion code in the perlop manpage.
  66.  
  67.   Regular Expressions
  68.  
  69.     The patterns used in pattern matching are regular expressions
  70.     such as those supplied in the Version 8 regex routines. (In
  71.     fact, the routines are derived (distantly) from Henry Spencer's
  72.     freely redistributable reimplementation of the V8 routines.) See
  73.     the Version 8 Regular Expressions manpage for details.
  74.  
  75.     In particular the following metacharacters have their standard
  76.     *egrep*-ish meanings:
  77.  
  78.         \    Quote the next metacharacter
  79.         ^    Match the beginning of the line
  80.         .    Match any character (except newline)
  81.         $    Match the end of the line (or before newline at the end)
  82.         |    Alternation
  83.         ()    Grouping
  84.         []    Character class
  85.  
  86.  
  87.     By default, the "^" character is guaranteed to match at only the
  88.     beginning of the string, the "$" character at only the end (or
  89.     before the newline at the end) and Perl does certain
  90.     optimizations with the assumption that the string contains only
  91.     one line. Embedded newlines will not be matched by "^" or "$".
  92.     You may, however, wish to treat a string as a multi-line buffer,
  93.     such that the "^" will match after any newline within the
  94.     string, and "$" will match before any newline. At the cost of a
  95.     little more overhead, you can do this by using the /m modifier
  96.     on the pattern match operator. (Older programs did this by
  97.     setting `$*', but this practice is now deprecated.)
  98.  
  99.     To facilitate multi-line substitutions, the "." character never
  100.     matches a newline unless you use the `/s' modifier, which in
  101.     effect tells Perl to pretend the string is a single line--even
  102.     if it isn't. The `/s' modifier also overrides the setting of
  103.     `$*', in case you have some (badly behaved) older code that sets
  104.     it in another module.
  105.  
  106.     The following standard quantifiers are recognized:
  107.  
  108.         *       Match 0 or more times
  109.         +       Match 1 or more times
  110.         ?       Match 1 or 0 times
  111.         {n}    Match exactly n times
  112.         {n,}   Match at least n times
  113.         {n,m}  Match at least n but not more than m times
  114.  
  115.  
  116.     (If a curly bracket occurs in any other context, it is treated
  117.     as a regular character.) The "*" modifier is equivalent to
  118.     `{0,}', the "+" modifier to `{1,}', and the "?" modifier to
  119.     `{0,1}'. n and m are limited to integral values less than a
  120.     preset limit defined when perl is built. This is usually 32766
  121.     on the most common platforms. The actual limit can be seen in
  122.     the error message generated by code such as this:
  123.  
  124.         $_ **= $_ , / {$_} / for 2 .. 42;
  125.  
  126.  
  127.     By default, a quantified subpattern is "greedy", that is, it
  128.     will match as many times as possible (given a particular
  129.     starting location) while still allowing the rest of the pattern
  130.     to match. If you want it to match the minimum number of times
  131.     possible, follow the quantifier with a "?". Note that the
  132.     meanings don't change, just the "greediness":
  133.  
  134.         *?       Match 0 or more times
  135.         +?       Match 1 or more times
  136.         ??       Match 0 or 1 time
  137.         {n}?   Match exactly n times
  138.         {n,}?  Match at least n times
  139.         {n,m}? Match at least n but not more than m times
  140.  
  141.  
  142.     Because patterns are processed as double quoted strings, the
  143.     following also work:
  144.  
  145.         \t        tab                   (HT, TAB)
  146.         \n        newline               (LF, NL)
  147.         \r        return                (CR)
  148.         \f        form feed             (FF)
  149.         \a        alarm (bell)          (BEL)
  150.         \e        escape (think troff)  (ESC)
  151.         \033    octal char (think of a PDP-11)
  152.         \x1B    hex char
  153.         \c[        control char
  154.         \l        lowercase next char (think vi)
  155.         \u        uppercase next char (think vi)
  156.         \L        lowercase till \E (think vi)
  157.         \U        uppercase till \E (think vi)
  158.         \E        end case modification (think vi)
  159.         \Q        quote (disable) pattern metacharacters till \E
  160.  
  161.  
  162.     If `use locale' is in effect, the case map used by `\l', `\L',
  163.     `\u' and `\U' is taken from the current locale. See the
  164.     perllocale manpage.
  165.  
  166.     You cannot include a literal `$' or `@' within a `\Q' sequence.
  167.     An unescaped `$' or `@' interpolates the corresponding variable,
  168.     while escaping will cause the literal string `\$' to be matched.
  169.     You'll need to write something like `m/\Quser\E\@\Qhost/'.
  170.  
  171.     In addition, Perl defines the following:
  172.  
  173.         \w    Match a "word" character (alphanumeric plus "_")
  174.         \W    Match a non-word character
  175.         \s    Match a whitespace character
  176.         \S    Match a non-whitespace character
  177.         \d    Match a digit character
  178.         \D    Match a non-digit character
  179.  
  180.  
  181.     A `\w' matches a single alphanumeric character, not a whole
  182.     word. To match a word you'd need to say `\w+'. If `use locale'
  183.     is in effect, the list of alphabetic characters generated by
  184.     `\w' is taken from the current locale. See the perllocale
  185.     manpage. You may use `\w', `\W', `\s', `\S', `\d', and `\D'
  186.     within character classes (though not as either end of a range).
  187.  
  188.     Perl defines the following zero-width assertions:
  189.  
  190.         \b    Match a word boundary
  191.         \B    Match a non-(word boundary)
  192.         \A    Match only at beginning of string
  193.         \Z    Match only at end of string, or before newline at the end
  194.         \z    Match only at end of string
  195.         \G    Match only where previous m//g left off (works only with /g)
  196.  
  197.  
  198.     A word boundary (`\b') is defined as a spot between two
  199.     characters that has a `\w' on one side of it and a `\W' on the
  200.     other side of it (in either order), counting the imaginary
  201.     characters off the beginning and end of the string as matching a
  202.     `\W'. (Within character classes `\b' represents backspace rather
  203.     than a word boundary.) The `\A' and `\Z' are just like "^" and
  204.     "$", except that they won't match multiple times when the `/m'
  205.     modifier is used, while "^" and "$" will match at every internal
  206.     line boundary. To match the actual end of the string, not
  207.     ignoring newline, you can use `\z'. The `\G' assertion can be
  208.     used to chain global matches (using `m//g'), as described in the
  209.     section on "Regexp Quote-Like Operators" in the perlop manpage.
  210.  
  211.     It is also useful when writing `lex'-like scanners, when you
  212.     have several patterns that you want to match against consequent
  213.     substrings of your string, see the previous reference. The
  214.     actual location where `\G' will match can also be influenced by
  215.     using `pos()' as an lvalue. See the "pos" entry in the perlfunc
  216.     manpage.
  217.  
  218.     When the bracketing construct `( ... )' is used, \<digit>
  219.     matches the digit'th substring. Outside of the pattern, always
  220.     use "$" instead of "\" in front of the digit. (While the
  221.     \<digit> notation can on rare occasion work outside the current
  222.     pattern, this should not be relied upon. See the WARNING below.)
  223.     The scope of $<digit> (and `$`', `$&', and `$'') extends to the
  224.     end of the enclosing BLOCK or eval string, or to the next
  225.     successful pattern match, whichever comes first. If you want to
  226.     use parentheses to delimit a subpattern (e.g., a set of
  227.     alternatives) without saving it as a subpattern, follow the (
  228.     with a ?:.
  229.  
  230.     You may have as many parentheses as you wish. If you have more
  231.     than 9 substrings, the variables $10, $11, ... refer to the
  232.     corresponding substring. Within the pattern, \10, \11, etc.
  233.     refer back to substrings if there have been at least that many
  234.     left parentheses before the backreference. Otherwise (for
  235.     backward compatibility) \10 is the same as \010, a backspace,
  236.     and \11 the same as \011, a tab. And so on. (\1 through \9 are
  237.     always backreferences.)
  238.  
  239.     `$+' returns whatever the last bracket match matched. `$&'
  240.     returns the entire matched string. (`$0' used to return the same
  241.     thing, but not any more.) `$`' returns everything before the
  242.     matched string. `$'' returns everything after the matched
  243.     string. Examples:
  244.  
  245.         s/^([^ ]*) *([^ ]*)/$2 $1/;     # swap first two words
  246.  
  247.         if (/Time: (..):(..):(..)/) {
  248.         $hours = $1;
  249.         $minutes = $2;
  250.         $seconds = $3;
  251.         }
  252.  
  253.  
  254.     Once perl sees that you need one of `$&', `$`' or `$'' anywhere
  255.     in the program, it has to provide them on each and every pattern
  256.     match. This can slow your program down. The same mechanism that
  257.     handles these provides for the use of $1, $2, etc., so you pay
  258.     the same price for each pattern that contains capturing
  259.     parentheses. But if you never use $&, etc., in your script, then
  260.     patterns *without* capturing parentheses won't be penalized. So
  261.     avoid $&, $', and $` if you can, but if you can't (and some
  262.     algorithms really appreciate them), once you've used them once,
  263.     use them at will, because you've already paid the price. As of
  264.     5.005, $& is not so costly as the other two.
  265.  
  266.     Backslashed metacharacters in Perl are alphanumeric, such as
  267.     `\b', `\w', `\n'. Unlike some other regular expression
  268.     languages, there are no backslashed symbols that aren't
  269.     alphanumeric. So anything that looks like \\, \(, \), \<, \>,
  270.     \{, or \} is always interpreted as a literal character, not a
  271.     metacharacter. This was once used in a common idiom to disable
  272.     or quote the special meanings of regular expression
  273.     metacharacters in a string that you want to use for a pattern.
  274.     Simply quote all non-alphanumeric characters:
  275.  
  276.         $pattern =~ s/(\W)/\\$1/g;
  277.  
  278.  
  279.     Now it is much more common to see either the quotemeta()
  280.     function or the `\Q' escape sequence used to disable all
  281.     metacharacters' special meanings like this:
  282.  
  283.         /$unquoted\Q$quoted\E$unquoted/
  284.  
  285.  
  286.     Perl defines a consistent extension syntax for regular
  287.     expressions. The syntax is a pair of parentheses with a question
  288.     mark as the first thing within the parentheses (this was a
  289.     syntax error in older versions of Perl). The character after the
  290.     question mark gives the function of the extension. Several
  291.     extensions are already supported:
  292.  
  293.     `(?#text)'
  294.               A comment. The text is ignored. If the `/x' switch is
  295.               used to enable whitespace formatting, a simple `#'
  296.               will suffice. Note that perl closes the comment as
  297.               soon as it sees a `)', so there is no way to put a
  298.               literal `)' in the comment.
  299.  
  300.     `(?:pattern)'
  301.  
  302.     `(?imsx-imsx:pattern)'
  303.               This is for clustering, not capturing; it groups
  304.               subexpressions like "()", but doesn't make
  305.               backreferences as "()" does. So
  306.  
  307.                   @fields = split(/\b(?:a|b|c)\b/)
  308.  
  309.  
  310.               is like
  311.  
  312.                   @fields = split(/\b(a|b|c)\b/)
  313.  
  314.  
  315.               but doesn't spit out extra fields.
  316.  
  317.               The letters between `?' and `:' act as flags
  318.               modifiers, see the `(?imsx-imsx)' manpage. In
  319.               particular,
  320.  
  321.                   /(?s-i:more.*than).*million/i
  322.  
  323.  
  324.               is equivalent to more verbose
  325.  
  326.                   /(?:(?s-i)more.*than).*million/i
  327.  
  328.  
  329.     `(?=pattern)'
  330.               A zero-width positive lookahead assertion. For
  331.               example, `/\w+(?=\t)/' matches a word followed by a
  332.               tab, without including the tab in `$&'.
  333.  
  334.     `(?!pattern)'
  335.               A zero-width negative lookahead assertion. For example
  336.               `/foo(?!bar)/' matches any occurrence of "foo" that
  337.               isn't followed by "bar". Note however that lookahead
  338.               and lookbehind are NOT the same thing. You cannot use
  339.               this for lookbehind.
  340.  
  341.               If you are looking for a "bar" that isn't preceded by
  342.               a "foo", `/(?!foo)bar/' will not do what you want.
  343.               That's because the `(?!foo)' is just saying that the
  344.               next thing cannot be "foo"--and it's not, it's a
  345.               "bar", so "foobar" will match. You would have to do
  346.               something like `/(?!foo)...bar/' for that. We say
  347.               "like" because there's the case of your "bar" not
  348.               having three characters before it. You could cover
  349.               that this way: `/(?:(?!foo)...|^.{0,2})bar/'.
  350.               Sometimes it's still easier just to say:
  351.  
  352.                   if (/bar/ && $` !~ /foo$/)
  353.  
  354.  
  355.               For lookbehind see below.
  356.  
  357.     `(?<=pattern)'
  358.               A zero-width positive lookbehind assertion. For
  359.               example, `/(?<=\t)\w+/' matches a word following a
  360.               tab, without including the tab in `$&'. Works only for
  361.               fixed-width lookbehind.
  362.  
  363.     `(?<!pattern)'
  364.               A zero-width negative lookbehind assertion. For
  365.               example `/(?<!bar)foo/' matches any occurrence of
  366.               "foo" that isn't following "bar". Works only for
  367.               fixed-width lookbehind.
  368.  
  369.     `(?{ code })'
  370.               Experimental "evaluate any Perl code" zero-width
  371.               assertion. Always succeeds. `code' is not
  372.               interpolated. Currently the rules to determine where
  373.               the `code' ends are somewhat convoluted.
  374.  
  375.               The `code' is properly scoped in the following sense:
  376.               if the assertion is backtracked (compare the section
  377.               on "Backtracking"), all the changes introduced after
  378.               `local'isation are undone, so
  379.  
  380.                 $_ = 'a' x 8;
  381.                 m< 
  382.                    (?{ $cnt = 0 })            # Initialize $cnt.
  383.                    (
  384.                      a 
  385.                      (?{
  386.                          local $cnt = $cnt + 1;    # Update $cnt, backtracking-safe.
  387.                      })
  388.                    )*  
  389.                    aaaa
  390.                    (?{ $res = $cnt })            # On success copy to non-localized
  391.                                   # location.
  392.                  >x;
  393.  
  394.  
  395.               will set `$res = 4'. Note that after the match $cnt
  396.               returns to the globally introduced value 0, since the
  397.               scopes which restrict `local' statements are unwound.
  398.  
  399.               This assertion may be used as the `(?(condition)yes-
  400.               pattern|no-pattern)' manpage switch. If *not* used in
  401.               this way, the result of evaluation of `code' is put
  402.               into variable $^R. This happens immediately, so $^R
  403.               can be used from other `(?{ code })' assertions inside
  404.               the same regular expression.
  405.  
  406.               The above assignment to $^R is properly localized,
  407.               thus the old value of $^R is restored if the assertion
  408.               is backtracked (compare the section on
  409.               "Backtracking").
  410.  
  411.               Due to security concerns, this construction is not
  412.               allowed if the regular expression involves run-time
  413.               interpolation of variables, unless `use re 'eval''
  414.               pragma is used (see the re manpage), or the variables
  415.               contain results of qr() operator (see the section on
  416.               "qr/STRING/imosx" in the perlop manpage).
  417.  
  418.               This restriction is due to the wide-spread
  419.               (questionable) practice of using the construct
  420.  
  421.                   $re = <>;
  422.                   chomp $re;
  423.                   $string =~ /$re/;
  424.  
  425.  
  426.               without tainting. While this code is frowned upon from
  427.               security point of view, when `(?{})' was introduced,
  428.               it was considered bad to add *new* security holes to
  429.               existing scripts.
  430.  
  431.               NOTE: Use of the above insecure snippet without also
  432.               enabling taint mode is to be severely frowned upon.
  433.               `use re 'eval'' does not disable tainting checks, thus
  434.               to allow $re in the above snippet to contain `(?{})'
  435.               *with tainting enabled*, one needs both `use re
  436.               'eval'' and untaint the $re.
  437.  
  438.     `(?>pattern)'
  439.               An "independent" subexpression. Matches the substring
  440.               that a *standalone* `pattern' would match if anchored
  441.               at the given position, and only this substring.
  442.  
  443.               Say, `^(?>a*)ab' will never match, since `(?>a*)'
  444.               (anchored at the beginning of string, as above) will
  445.               match *all* characters `a' at the beginning of string,
  446.               leaving no `a' for `ab' to match. In contrast, `a*ab'
  447.               will match the same as `a+b', since the match of the
  448.               subgroup `a*' is influenced by the following group
  449.               `ab' (see the section on "Backtracking"). In
  450.               particular, `a*' inside `a*ab' will match fewer
  451.               characters than a standalone `a*', since this makes
  452.               the tail match.
  453.  
  454.               An effect similar to `(?>pattern)' may be achieved by
  455.  
  456.                  (?=(pattern))\1
  457.  
  458.  
  459.               since the lookahead is in *"logical"* context, thus
  460.               matches the same substring as a standalone `a+'. The
  461.               following `\1' eats the matched string, thus making a
  462.               zero-length assertion into an analogue of `(?>...)'.
  463.               (The difference between these two constructs is that
  464.               the second one uses a catching group, thus shifting
  465.               ordinals of backreferences in the rest of a regular
  466.               expression.)
  467.  
  468.               This construct is useful for optimizations of
  469.               "eternal" matches, because it will not backtrack (see
  470.               the section on "Backtracking").
  471.  
  472.                   m{ \(
  473.                     ( 
  474.                       [^()]+ 
  475.                         | 
  476.                           \( [^()]* \)
  477.                         )+
  478.                      \) 
  479.                    }x
  480.  
  481.  
  482.               That will efficiently match a nonempty group with
  483.               matching two-or-less-level-deep parentheses. However,
  484.               if there is no such group, it will take virtually
  485.               forever on a long string. That's because there are so
  486.               many different ways to split a long string into
  487.               several substrings. This is what `(.+)+' is doing, and
  488.               `(.+)+' is similar to a subpattern of the above
  489.               pattern. Consider that the above pattern detects no-
  490.               match on `((()aaaaaaaaaaaaaaaaaa' in several seconds,
  491.               but that each extra letter doubles this time. This
  492.               exponential performance will make it appear that your
  493.               program has hung.
  494.  
  495.               However, a tiny modification of this pattern
  496.  
  497.                   m{ \( 
  498.                     ( 
  499.                       (?> [^()]+ )
  500.                         | 
  501.                           \( [^()]* \)
  502.                         )+
  503.                      \) 
  504.                    }x
  505.  
  506.  
  507.               which uses `(?>...)' matches exactly when the one
  508.               above does (verifying this yourself would be a
  509.               productive exercise), but finishes in a fourth the
  510.               time when used on a similar string with 1000000 `a's.
  511.               Be aware, however, that this pattern currently
  512.               triggers a warning message under -w saying it
  513.               `"matches the null string many times"'):
  514.  
  515.               On simple groups, such as the pattern `(?> [^()]+ )',
  516.               a comparable effect may be achieved by negative
  517.               lookahead, as in `[^()]+ (?! [^()] )'. This was only 4
  518.               times slower on a string with 1000000 `a's.
  519.  
  520.     `(?(condition)yes-pattern|no-pattern)'
  521.  
  522.     `(?(condition)yes-pattern)'
  523.               Conditional expression. `(condition)' should be either
  524.               an integer in parentheses (which is valid if the
  525.               corresponding pair of parentheses matched), or
  526.               lookahead/lookbehind/evaluate zero-width assertion.
  527.  
  528.               Say,
  529.  
  530.                   m{ ( \( )? 
  531.                      [^()]+ 
  532.                      (?(1) \) ) 
  533.                    }x
  534.  
  535.  
  536.               matches a chunk of non-parentheses, possibly included
  537.               in parentheses themselves.
  538.  
  539.     `(?imsx-imsx)'
  540.               One or more embedded pattern-match modifiers. This is
  541.               particularly useful for patterns that are specified in
  542.               a table somewhere, some of which want to be case
  543.               sensitive, and some of which don't. The case
  544.               insensitive ones need to include merely `(?i)' at the
  545.               front of the pattern. For example:
  546.  
  547.                   $pattern = "foobar";
  548.                   if ( /$pattern/i ) { } 
  549.  
  550.                   # more flexible:
  551.  
  552.                   $pattern = "(?i)foobar";
  553.                   if ( /$pattern/ ) { } 
  554.  
  555.  
  556.               Letters after `-' switch modifiers off.
  557.  
  558.               These modifiers are localized inside an enclosing
  559.               group (if any). Say,
  560.  
  561.                   ( (?i) blah ) \s+ \1
  562.  
  563.  
  564.               (assuming `x' modifier, and no `i' modifier outside of
  565.               this group) will match a repeated (*including the
  566.               case*!) word `blah' in any case.
  567.  
  568.  
  569.     A question mark was chosen for this and for the new minimal-
  570.     matching construct because 1) question mark is pretty rare in
  571.     older regular expressions, and 2) whenever you see one, you
  572.     should stop and "question" exactly what is going on. That's
  573.     psychology...
  574.  
  575.   Backtracking
  576.  
  577.     A fundamental feature of regular expression matching involves
  578.     the notion called *backtracking*, which is currently used (when
  579.     needed) by all regular expression quantifiers, namely `*', `*?',
  580.     `+', `+?', `{n,m}', and `{n,m}?'.
  581.  
  582.     For a regular expression to match, the *entire* regular
  583.     expression must match, not just part of it. So if the beginning
  584.     of a pattern containing a quantifier succeeds in a way that
  585.     causes later parts in the pattern to fail, the matching engine
  586.     backs up and recalculates the beginning part--that's why it's
  587.     called backtracking.
  588.  
  589.     Here is an example of backtracking: Let's say you want to find
  590.     the word following "foo" in the string "Food is on the foo
  591.     table.":
  592.  
  593.         $_ = "Food is on the foo table.";
  594.         if ( /\b(foo)\s+(\w+)/i ) {
  595.         print "$2 follows $1.\n";
  596.         }
  597.  
  598.  
  599.     When the match runs, the first part of the regular expression
  600.     (`\b(foo)') finds a possible match right at the beginning of the
  601.     string, and loads up $1 with "Foo". However, as soon as the
  602.     matching engine sees that there's no whitespace following the
  603.     "Foo" that it had saved in $1, it realizes its mistake and
  604.     starts over again one character after where it had the tentative
  605.     match. This time it goes all the way until the next occurrence
  606.     of "foo". The complete regular expression matches this time, and
  607.     you get the expected output of "table follows foo."
  608.  
  609.     Sometimes minimal matching can help a lot. Imagine you'd like to
  610.     match everything between "foo" and "bar". Initially, you write
  611.     something like this:
  612.  
  613.         $_ =  "The food is under the bar in the barn.";
  614.         if ( /foo(.*)bar/ ) {
  615.         print "got <$1>\n";
  616.         }
  617.  
  618.  
  619.     Which perhaps unexpectedly yields:
  620.  
  621.       got <d is under the bar in the >
  622.  
  623.  
  624.     That's because `.*' was greedy, so you get everything between
  625.     the *first* "foo" and the *last* "bar". In this case, it's more
  626.     effective to use minimal matching to make sure you get the text
  627.     between a "foo" and the first "bar" thereafter.
  628.  
  629.         if ( /foo(.*?)bar/ ) { print "got <$1>\n" }
  630.       got <d is under the >
  631.  
  632.  
  633.     Here's another example: let's say you'd like to match a number
  634.     at the end of a string, and you also want to keep the preceding
  635.     part the match. So you write this:
  636.  
  637.         $_ = "I have 2 numbers: 53147";
  638.         if ( /(.*)(\d*)/ ) {                # Wrong!
  639.         print "Beginning is <$1>, number is <$2>.\n";
  640.         }
  641.  
  642.  
  643.     That won't work at all, because `.*' was greedy and gobbled up
  644.     the whole string. As `\d*' can match on an empty string the
  645.     complete regular expression matched successfully.
  646.  
  647.         Beginning is <I have 2 numbers: 53147>, number is <>.
  648.  
  649.  
  650.     Here are some variants, most of which don't work:
  651.  
  652.         $_ = "I have 2 numbers: 53147";
  653.         @pats = qw{
  654.         (.*)(\d*)
  655.         (.*)(\d+)
  656.         (.*?)(\d*)
  657.         (.*?)(\d+)
  658.         (.*)(\d+)$
  659.         (.*?)(\d+)$
  660.         (.*)\b(\d+)$
  661.         (.*\D)(\d+)$
  662.         };
  663.  
  664.         for $pat (@pats) {
  665.         printf "%-12s ", $pat;
  666.         if ( /$pat/ ) {
  667.             print "<$1> <$2>\n";
  668.         } else {
  669.             print "FAIL\n";
  670.         }
  671.         }
  672.  
  673.  
  674.     That will print out:
  675.  
  676.         (.*)(\d*)    <I have 2 numbers: 53147> <>
  677.         (.*)(\d+)    <I have 2 numbers: 5314> <7>
  678.         (.*?)(\d*)   <> <>
  679.         (.*?)(\d+)   <I have > <2>
  680.         (.*)(\d+)$   <I have 2 numbers: 5314> <7>
  681.         (.*?)(\d+)$  <I have 2 numbers: > <53147>
  682.         (.*)\b(\d+)$ <I have 2 numbers: > <53147>
  683.         (.*\D)(\d+)$ <I have 2 numbers: > <53147>
  684.  
  685.  
  686.     As you see, this can be a bit tricky. It's important to realize
  687.     that a regular expression is merely a set of assertions that
  688.     gives a definition of success. There may be 0, 1, or several
  689.     different ways that the definition might succeed against a
  690.     particular string. And if there are multiple ways it might
  691.     succeed, you need to understand backtracking to know which
  692.     variety of success you will achieve.
  693.  
  694.     When using lookahead assertions and negations, this can all get
  695.     even tricker. Imagine you'd like to find a sequence of non-
  696.     digits not followed by "123". You might try to write that as
  697.  
  698.         $_ = "ABC123";
  699.         if ( /^\D*(?!123)/ ) {        # Wrong!
  700.         print "Yup, no 123 in $_\n";
  701.         }
  702.  
  703.  
  704.     But that isn't going to match; at least, not the way you're
  705.     hoping. It claims that there is no 123 in the string. Here's a
  706.     clearer picture of why it that pattern matches, contrary to
  707.     popular expectations:
  708.  
  709.         $x = 'ABC123' ;
  710.         $y = 'ABC445' ;
  711.  
  712.         print "1: got $1\n" if $x =~ /^(ABC)(?!123)/ ;
  713.         print "2: got $1\n" if $y =~ /^(ABC)(?!123)/ ;
  714.  
  715.         print "3: got $1\n" if $x =~ /^(\D*)(?!123)/ ;
  716.         print "4: got $1\n" if $y =~ /^(\D*)(?!123)/ ;
  717.  
  718.  
  719.     This prints
  720.  
  721.         2: got ABC
  722.         3: got AB
  723.         4: got ABC
  724.  
  725.  
  726.     You might have expected test 3 to fail because it seems to a
  727.     more general purpose version of test 1. The important difference
  728.     between them is that test 3 contains a quantifier (`\D*') and so
  729.     can use backtracking, whereas test 1 will not. What's happening
  730.     is that you've asked "Is it true that at the start of $x,
  731.     following 0 or more non-digits, you have something that's not
  732.     123?" If the pattern matcher had let `\D*' expand to "ABC", this
  733.     would have caused the whole pattern to fail. The search engine
  734.     will initially match `\D*' with "ABC". Then it will try to match
  735.     `(?!123' with "123", which of course fails. But because a
  736.     quantifier (`\D*') has been used in the regular expression, the
  737.     search engine can backtrack and retry the match differently in
  738.     the hope of matching the complete regular expression.
  739.  
  740.     The pattern really, *really* wants to succeed, so it uses the
  741.     standard pattern back-off-and-retry and lets `\D*' expand to
  742.     just "AB" this time. Now there's indeed something following "AB"
  743.     that is not "123". It's in fact "C123", which suffices.
  744.  
  745.     We can deal with this by using both an assertion and a negation.
  746.     We'll say that the first part in $1 must be followed by a digit,
  747.     and in fact, it must also be followed by something that's not
  748.     "123". Remember that the lookaheads are zero-width expressions--
  749.     they only look, but don't consume any of the string in their
  750.     match. So rewriting this way produces what you'd expect; that
  751.     is, case 5 will fail, but case 6 succeeds:
  752.  
  753.         print "5: got $1\n" if $x =~ /^(\D*)(?=\d)(?!123)/ ;
  754.         print "6: got $1\n" if $y =~ /^(\D*)(?=\d)(?!123)/ ;
  755.  
  756.         6: got ABC
  757.  
  758.  
  759.     In other words, the two zero-width assertions next to each other
  760.     work as though they're ANDed together, just as you'd use any
  761.     builtin assertions: `/^$/' matches only if you're at the
  762.     beginning of the line AND the end of the line simultaneously.
  763.     The deeper underlying truth is that juxtaposition in regular
  764.     expressions always means AND, except when you write an explicit
  765.     OR using the vertical bar. `/ab/' means match "a" AND (then)
  766.     match "b", although the attempted matches are made at different
  767.     positions because "a" is not a zero-width assertion, but a one-
  768.     width assertion.
  769.  
  770.     One warning: particularly complicated regular expressions can
  771.     take exponential time to solve due to the immense number of
  772.     possible ways they can use backtracking to try match. For
  773.     example this will take a very long time to run
  774.  
  775.         /((a{0,5}){0,5}){0,5}/
  776.  
  777.  
  778.     And if you used `*''s instead of limiting it to 0 through 5
  779.     matches, then it would take literally forever--or until you ran
  780.     out of stack space.
  781.  
  782.     A powerful tool for optimizing such beasts is "independent"
  783.     groups, which do not backtrace (see the `(?>pattern)' manpage).
  784.     Note also that zero-length lookahead/lookbehind assertions will
  785.     not backtrace to make the tail match, since they are in
  786.     "logical" context: only the fact whether they match or not is
  787.     considered relevant. For an example where side-effects of a
  788.     lookahead *might* have influenced the following match, see the
  789.     `(?>pattern)' manpage.
  790.  
  791.   Version 8 Regular Expressions
  792.  
  793.     In case you're not familiar with the "regular" Version 8 regex
  794.     routines, here are the pattern-matching rules not described
  795.     above.
  796.  
  797.     Any single character matches itself, unless it is a
  798.     *metacharacter* with a special meaning described here or above.
  799.     You can cause characters that normally function as
  800.     metacharacters to be interpreted literally by prefixing them
  801.     with a "\" (e.g., "\." matches a ".", not any character; "\\"
  802.     matches a "\"). A series of characters matches that series of
  803.     characters in the target string, so the pattern `blurfl' would
  804.     match "blurfl" in the target string.
  805.  
  806.     You can specify a character class, by enclosing a list of
  807.     characters in `[]', which will match any one character from the
  808.     list. If the first character after the "[" is "^", the class
  809.     matches any character not in the list. Within a list, the "-"
  810.     character is used to specify a range, so that `a-z' represents
  811.     all characters between "a" and "z", inclusive. If you want "-"
  812.     itself to be a member of a class, put it at the start or end of
  813.     the list, or escape it with a backslash. (The following all
  814.     specify the same class of three characters: `[-az]', `[az-]',
  815.     and `[a\-z]'. All are different from `[a-z]', which specifies a
  816.     class containing twenty-six characters.)
  817.  
  818.     Note also that the whole range idea is rather unportable between
  819.     character sets--and even within character sets they may cause
  820.     results you probably didn't expect. A sound principle is to use
  821.     only ranges that begin from and end at either alphabets of equal
  822.     case ([a-e], [A-E]), or digits ([0-9]). Anything else is unsafe.
  823.     If in doubt, spell out the character sets in full.
  824.  
  825.     Characters may be specified using a metacharacter syntax much
  826.     like that used in C: "\n" matches a newline, "\t" a tab, "\r" a
  827.     carriage return, "\f" a form feed, etc. More generally, \*nnn*,
  828.     where *nnn* is a string of octal digits, matches the character
  829.     whose ASCII value is *nnn*. Similarly, \x*nn*, where *nn* are
  830.     hexadecimal digits, matches the character whose ASCII value is
  831.     *nn*. The expression \c*x* matches the ASCII character control-
  832.     *x*. Finally, the "." metacharacter matches any character except
  833.     "\n" (unless you use `/s').
  834.  
  835.     You can specify a series of alternatives for a pattern using "|"
  836.     to separate them, so that `fee|fie|foe' will match any of "fee",
  837.     "fie", or "foe" in the target string (as would `f(e|i|o)e'). The
  838.     first alternative includes everything from the last pattern
  839.     delimiter ("(", "[", or the beginning of the pattern) up to the
  840.     first "|", and the last alternative contains everything from the
  841.     last "|" to the next pattern delimiter. For this reason, it's
  842.     common practice to include alternatives in parentheses, to
  843.     minimize confusion about where they start and end.
  844.  
  845.     Alternatives are tried from left to right, so the first
  846.     alternative found for which the entire expression matches, is
  847.     the one that is chosen. This means that alternatives are not
  848.     necessarily greedy. For example: when matching `foo|foot'
  849.     against "barefoot", only the "foo" part will match, as that is
  850.     the first alternative tried, and it successfully matches the
  851.     target string. (This might not seem important, but it is
  852.     important when you are capturing matched text using
  853.     parentheses.)
  854.  
  855.     Also remember that "|" is interpreted as a literal within square
  856.     brackets, so if you write `[fee|fie|foe]' you're really only
  857.     matching `[feio|]'.
  858.  
  859.     Within a pattern, you may designate subpatterns for later
  860.     reference by enclosing them in parentheses, and you may refer
  861.     back to the *n*th subpattern later in the pattern using the
  862.     metacharacter \*n*. Subpatterns are numbered based on the left
  863.     to right order of their opening parenthesis. A backreference
  864.     matches whatever actually matched the subpattern in the string
  865.     being examined, not the rules for that subpattern. Therefore,
  866.     `(0|0x)\d*\s\1\d*' will match "0x1234 0x4321", but not "0x1234
  867.     01234", because subpattern 1 actually matched "0x", even though
  868.     the rule `0|0x' could potentially match the leading 0 in the
  869.     second number.
  870.  
  871.   WARNING on \1 vs $1
  872.  
  873.     Some people get too used to writing things like:
  874.  
  875.         $pattern =~ s/(\W)/\\\1/g;
  876.  
  877.  
  878.     This is grandfathered for the RHS of a substitute to avoid
  879.     shocking the sed addicts, but it's a dirty habit to get into.
  880.     That's because in PerlThink, the righthand side of a `s///' is a
  881.     double-quoted string. `\1' in the usual double-quoted string
  882.     means a control-A. The customary Unix meaning of `\1' is kludged
  883.     in for `s///'. However, if you get into the habit of doing that,
  884.     you get yourself into trouble if you then add an `/e' modifier.
  885.  
  886.         s/(\d+)/ \1 + 1 /eg;        # causes warning under -w
  887.  
  888.  
  889.     Or if you try to do
  890.  
  891.         s/(\d+)/\1000/;
  892.  
  893.  
  894.     You can't disambiguate that by saying `\{1}000', whereas you can
  895.     fix it with `${1}000'. Basically, the operation of interpolation
  896.     should not be confused with the operation of matching a
  897.     backreference. Certainly they mean two different things on the
  898.     *left* side of the `s///'.
  899.  
  900.   Repeated patterns matching zero-length substring
  901.  
  902.     WARNING: Difficult material (and prose) ahead. This section
  903.     needs a rewrite.
  904.  
  905.     Regular expressions provide a terse and powerful programming
  906.     language. As with most other power tools, power comes together
  907.     with the ability to wreak havoc.
  908.  
  909.     A common abuse of this power stems from the ability to make
  910.     infinite loops using regular expressions, with something as
  911.     innocuous as:
  912.  
  913.         'foo' =~ m{ ( o? )* }x;
  914.  
  915.  
  916.     The `o?' can match at the beginning of `'foo'', and since the
  917.     position in the string is not moved by the match, `o?' would
  918.     match again and again due to the `*' modifier. Another common
  919.     way to create a similar cycle is with the looping modifier
  920.     `//g':
  921.  
  922.         @matches = ( 'foo' =~ m{ o? }xg );
  923.  
  924.  
  925.     or
  926.  
  927.         print "match: <$&>\n" while 'foo' =~ m{ o? }xg;
  928.  
  929.  
  930.     or the loop implied by split().
  931.  
  932.     However, long experience has shown that many programming tasks
  933.     may be significantly simplified by using repeated subexpressions
  934.     which may match zero-length substrings, with a simple example
  935.     being:
  936.  
  937.         @chars = split //, $string;          # // is not magic in split
  938.         ($whitewashed = $string) =~ s/()/ /g; # parens avoid magic s// /
  939.  
  940.  
  941.     Thus Perl allows the `/()/' construct, which *forcefully breaks
  942.     the infinite loop*. The rules for this are different for lower-
  943.     level loops given by the greedy modifiers `*+{}', and for
  944.     higher-level ones like the `/g' modifier or split() operator.
  945.  
  946.     The lower-level loops are *interrupted* when it is detected that
  947.     a repeated expression did match a zero-length substring, thus
  948.  
  949.        m{ (?: NON_ZERO_LENGTH | ZERO_LENGTH )* }x;
  950.  
  951.  
  952.     is made equivalent to
  953.  
  954.        m{   (?: NON_ZERO_LENGTH )* 
  955.           | 
  956.             (?: ZERO_LENGTH )? 
  957.         }x;
  958.  
  959.  
  960.     The higher level-loops preserve an additional state between
  961.     iterations: whether the last match was zero-length. To break the
  962.     loop, the following match after a zero-length match is
  963.     prohibited to have a length of zero. This prohibition interacts
  964.     with backtracking (see the section on "Backtracking"), and so
  965.     the *second best* match is chosen if the *best* match is of zero
  966.     length.
  967.  
  968.     Say,
  969.  
  970.         $_ = 'bar';
  971.         s/\w??/<$&>/g;
  972.  
  973.  
  974.     results in `"<'<b><><a><><r><>">. At each position of the string
  975.     the best match given by non-greedy `??' is the zero-length
  976.     match, and the *second best* match is what is matched by `\w'.
  977.     Thus zero-length matches alternate with one-character-long
  978.     matches.
  979.  
  980.     Similarly, for repeated `m/()/g' the second-best match is the
  981.     match at the position one notch further in the string.
  982.  
  983.     The additional state of being *matched with zero-length* is
  984.     associated to the matched string, and is reset by each
  985.     assignment to pos().
  986.  
  987.   Creating custom RE engines
  988.  
  989.     Overloaded constants (see the overload manpage) provide a simple
  990.     way to extend the functionality of the RE engine.
  991.  
  992.     Suppose that we want to enable a new RE escape-sequence `\Y|'
  993.     which matches at boundary between white-space characters and
  994.     non-whitespace characters. Note that
  995.     `(?=\S)(?<!\S)|(?!\S)(?<=\S)' matches exactly at these
  996.     positions, so we want to have each `\Y|' in the place of the
  997.     more complicated version. We can create a module `customre' to
  998.     do this:
  999.  
  1000.         package customre;
  1001.         use overload;
  1002.  
  1003.         sub import {
  1004.           shift;
  1005.           die "No argument to customre::import allowed" if @_;
  1006.           overload::constant 'qr' => \&convert;
  1007.         }
  1008.  
  1009.         sub invalid { die "/$_[0]/: invalid escape '\\$_[1]'"}
  1010.  
  1011.         my %rules = ( '\\' => '\\', 
  1012.               'Y|' => qr/(?=\S)(?<!\S)|(?!\S)(?<=\S)/ );
  1013.         sub convert {
  1014.           my $re = shift;
  1015.           $re =~ s{ 
  1016.                     \\ ( \\ | Y . )
  1017.                   }
  1018.                   { $rules{$1} or invalid($re,$1) }sgex; 
  1019.           return $re;
  1020.         }
  1021.  
  1022.  
  1023.     Now `use customre' enables the new escape in constant regular
  1024.     expressions, i.e., those without any runtime variable
  1025.     interpolations. As documented in the overload manpage, this
  1026.     conversion will work only over literal parts of regular
  1027.     expressions. For `\Y|$re\Y|' the variable part of this regular
  1028.     expression needs to be converted explicitly (but only if the
  1029.     special meaning of `\Y|' should be enabled inside $re):
  1030.  
  1031.         use customre;
  1032.         $re = <>;
  1033.         chomp $re;
  1034.         $re = customre::convert $re;
  1035.         /\Y|$re\Y|/;
  1036.  
  1037.  
  1038.   SEE ALSO
  1039.  
  1040.     the section on "Regexp Quote-Like Operators" in the perlop
  1041.     manpage.
  1042.  
  1043.     the section on "Gory details of parsing quoted constructs" in
  1044.     the perlop manpage.
  1045.  
  1046.     the "pos" entry in the perlfunc manpage.
  1047.  
  1048.     the perllocale manpage.
  1049.  
  1050.     *Mastering Regular Expressions* (see the perlbook manpage) by
  1051.     Jeffrey Friedl.
  1052.  
  1053.