home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / perl502b.zip / pod / perlre.pod < prev    next >
Text File  |  1996-01-30  |  22KB  |  532 lines

  1. =head1 NAME
  2.  
  3. perlre - Perl regular expressions
  4.  
  5. =head1 DESCRIPTION
  6.  
  7. This page describes the syntax of regular expressions in Perl.  For a
  8. description of how to actually I<use> regular expressions in matching
  9. operations, plus various examples of the same, see C<m//> and C<s///> in
  10. L<perlop>.
  11.  
  12. The matching operations can
  13. have various modifiers, some of which relate to the interpretation of
  14. the regular expression inside.  These are:
  15.  
  16.     i   Do case-insensitive pattern matching.
  17.     m   Treat string as multiple lines.
  18.     s   Treat string as single line.
  19.     x   Extend your pattern's legibility with whitespace and comments.
  20.  
  21. These are usually written as "the C</x> modifier", even though the delimiter
  22. in question might not actually be a slash.  In fact, any of these
  23. modifiers may also be embedded within the regular expression itself using
  24. the new C<(?...)> construct.  See below.
  25.  
  26. The C</x> modifier itself needs a little more explanation.  It tells
  27. the regular expression parser to ignore whitespace that is not
  28. backslashed or within a character class.  You can use this to break up
  29. your regular expression into (slightly) more readable parts.  The C<#>
  30. character is also treated as a metacharacter introducing a comment,
  31. just as in ordinary Perl code.  Taken together, these features go a
  32. long way towards making Perl 5 a readable language.  See the C comment
  33. deletion code in L<perlop>.
  34.  
  35. =head2 Regular Expressions
  36.  
  37. The patterns used in pattern matching are regular expressions such as
  38. those supplied in the Version 8 regexp routines.  (In fact, the
  39. routines are derived (distantly) from Henry Spencer's freely
  40. redistributable reimplementation of the V8 routines.)
  41. See L<Version 8 Regular Expressions> for details.
  42.  
  43. In particular the following metacharacters have their standard I<egrep>-ish
  44. meanings:
  45.  
  46.     \    Quote the next metacharacter
  47.     ^    Match the beginning of the line
  48.     .    Match any character (except newline)
  49.     $    Match the end of the line (or before newline at the end)
  50.     |    Alternation
  51.     ()    Grouping
  52.     []    Character class
  53.  
  54. By default, the "^" character is guaranteed to match only at the
  55. beginning of the string, the "$" character only at the end (or before the
  56. newline at the end) and Perl does certain optimizations with the
  57. assumption that the string contains only one line.  Embedded newlines
  58. will not be matched by "^" or "$".  You may, however, wish to treat a
  59. string as a multi-line buffer, such that the "^" will match after any
  60. newline within the string, and "$" will match before any newline.  At the
  61. cost of a little more overhead, you can do this by using the /m modifier
  62. on the pattern match operator.  (Older programs did this by setting C<$*>,
  63. but this practice is deprecated in Perl 5.)
  64.  
  65. To facilitate multi-line substitutions, the "." character never matches a
  66. newline unless you use the C</s> modifier, which tells Perl to pretend
  67. the string is a single line--even if it isn't.  The C</s> modifier also
  68. overrides the setting of C<$*>, in case you have some (badly behaved) older
  69. code that sets it in another module.
  70.  
  71. The following standard quantifiers are recognized:
  72.  
  73.     *       Match 0 or more times
  74.     +       Match 1 or more times
  75.     ?       Match 1 or 0 times
  76.     {n}    Match exactly n times
  77.     {n,}   Match at least n times
  78.     {n,m}  Match at least n but not more than m times
  79.  
  80. (If a curly bracket occurs in any other context, it is treated
  81. as a regular character.)  The "*" modifier is equivalent to C<{0,}>, the "+"
  82. modifier to C<{1,}>, and the "?" modifier to C<{0,1}>.  n and m are limited
  83. to integral values less than 65536.
  84.  
  85. By default, a quantified subpattern is "greedy", that is, it will match as
  86. many times as possible without causing the rest pattern not to match.  The
  87. standard quantifiers are all "greedy", in that they match as many
  88. occurrences as possible (given a particular starting location) without
  89. causing the pattern to fail.  If you want it to match the minimum number
  90. of times possible, follow the quantifier with a "?" after any of them.
  91. Note that the meanings don't change, just the "gravity":
  92.  
  93.     *?       Match 0 or more times
  94.     +?       Match 1 or more times
  95.     ??       Match 0 or 1 time
  96.     {n}?   Match exactly n times
  97.     {n,}?  Match at least n times
  98.     {n,m}? Match at least n but not more than m times
  99.  
  100. Since patterns are processed as double quoted strings, the following
  101. also work:
  102.  
  103.     \t        tab
  104.     \n        newline
  105.     \r        return
  106.     \f        form feed
  107.     \v        vertical tab, whatever that is
  108.     \a        alarm (bell)
  109.     \e        escape (think troff)
  110.     \033    octal char (think of a PDP-11)
  111.     \x1B    hex char
  112.     \c[        control char
  113.     \l        lowercase next char (think vi)
  114.     \u        uppercase next char (think vi)
  115.     \L        lowercase till \E (think vi)
  116.     \U        uppercase till \E (think vi)
  117.     \E        end case modification (think vi)
  118.     \Q        quote regexp metacharacters till \E
  119.  
  120. In addition, Perl defines the following:
  121.  
  122.     \w    Match a "word" character (alphanumeric plus "_")
  123.     \W    Match a non-word character
  124.     \s    Match a whitespace character
  125.     \S    Match a non-whitespace character
  126.     \d    Match a digit character
  127.     \D    Match a non-digit character
  128.  
  129. Note that C<\w> matches a single alphanumeric character, not a whole
  130. word.  To match a word you'd need to say C<\w+>.  You may use C<\w>,
  131. C<\W>, C<\s>, C<\S>, C<\d> and C<\D> within character classes (though not
  132. as either end of a range).
  133.  
  134. Perl defines the following zero-width assertions:
  135.  
  136.     \b    Match a word boundary
  137.     \B    Match a non-(word boundary)
  138.     \A    Match only at beginning of string
  139.     \Z    Match only at end of string (or before newline at the end)
  140.     \G    Match only where previous m//g left off
  141.  
  142. A word boundary (C<\b>) is defined as a spot between two characters that
  143. has a C<\w> on one side of it and and a C<\W> on the other side of it (in
  144. either order), counting the imaginary characters off the beginning and
  145. end of the string as matching a C<\W>.  (Within character classes C<\b>
  146. represents backspace rather than a word boundary.)  The C<\A> and C<\Z> are
  147. just like "^" and "$" except that they won't match multiple times when the
  148. C</m> modifier is used, while "^" and "$" will match at every internal line
  149. boundary.  To match the actual end of the string, not ignoring newline,
  150. you can use C<\Z(?!\n)>.
  151.  
  152. When the bracketing construct C<( ... )> is used, \<digit> matches the
  153. digit'th substring.  Outside of the pattern, always use "$" instead of "\"
  154. in front of the digit.  (The \<digit> notation can on rare occasion work
  155. outside the current pattern, this should not be relied upon.  See the
  156. WARNING below.) The scope of $<digit> (and C<$`>, C<$&>, and C<$')>
  157. extends to the end of the enclosing BLOCK or eval string, or to the next
  158. successful pattern match, whichever comes first.  If you want to use
  159. parentheses to delimit subpattern (e.g. a set of alternatives) without
  160. saving it as a subpattern, follow the ( with a ?.
  161.  
  162. You may have as many parentheses as you wish.  If you have more
  163. than 9 substrings, the variables $10, $11, ... refer to the
  164. corresponding substring.  Within the pattern, \10, \11, etc. refer back
  165. to substrings if there have been at least that many left parens before
  166. the backreference.  Otherwise (for backward compatibility) \10 is the
  167. same as \010, a backspace, and \11 the same as \011, a tab.  And so
  168. on.  (\1 through \9 are always backreferences.)
  169.  
  170. C<$+> returns whatever the last bracket match matched.  C<$&> returns the
  171. entire matched string.  ($0 used to return the same thing, but not any
  172. more.)  C<$`> returns everything before the matched string.  C<$'> returns
  173. everything after the matched string.  Examples:
  174.  
  175.     s/^([^ ]*) *([^ ]*)/$2 $1/;     # swap first two words
  176.  
  177.     if (/Time: (..):(..):(..)/) {
  178.     $hours = $1;
  179.     $minutes = $2;
  180.     $seconds = $3;
  181.     }
  182.  
  183. You will note that all backslashed metacharacters in Perl are
  184. alphanumeric, such as C<\b>, C<\w>, C<\n>.  Unlike some other regular expression
  185. languages, there are no backslashed symbols that aren't alphanumeric.
  186. So anything that looks like \\, \(, \), \<, \>, \{, or \} is always
  187. interpreted as a literal character, not a metacharacter.  This makes it
  188. simple to quote a string that you want to use for a pattern but that
  189. you are afraid might contain metacharacters.  Simply quote all the
  190. non-alphanumeric characters:
  191.  
  192.     $pattern =~ s/(\W)/\\$1/g;
  193.  
  194. You can also use the built-in quotemeta() function to do this.
  195. An even easier way to quote metacharacters right in the match operator
  196. is to say
  197.  
  198.     /$unquoted\Q$quoted\E$unquoted/
  199.  
  200. Perl 5 defines a consistent extension syntax for regular expressions.
  201. The syntax is a pair of parens with a question mark as the first thing
  202. within the parens (this was a syntax error in Perl 4).  The character
  203. after the question mark gives the function of the extension.  Several
  204. extensions are already supported:
  205.  
  206. =over 10
  207.  
  208. =item (?#text)
  209.  
  210. A comment.  The text is ignored.  If the C</x> switch is used to enable
  211. whitespace formatting, a simple C<#> will suffice.
  212.  
  213. =item (?:regexp)
  214.  
  215. This groups things like "()" but doesn't make backrefences like "()" does.  So
  216.  
  217.     split(/\b(?:a|b|c)\b/)
  218.  
  219. is like
  220.  
  221.     split(/\b(a|b|c)\b/)
  222.  
  223. but doesn't spit out extra fields.
  224.  
  225. =item (?=regexp)
  226.  
  227. A zero-width positive lookahead assertion.  For example, C</\w+(?=\t)/>
  228. matches a word followed by a tab, without including the tab in C<$&>.
  229.  
  230. =item (?!regexp)
  231.  
  232. A zero-width negative lookahead assertion.  For example C</foo(?!bar)/>
  233. matches any occurrence of "foo" that isn't followed by "bar".  Note
  234. however that lookahead and lookbehind are NOT the same thing.  You cannot
  235. use this for lookbehind: C</(?!foo)bar/> will not find an occurrence of
  236. "bar" that is preceded by something which is not "foo".  That's because
  237. the C<(?!foo)> is just saying that the next thing cannot be "foo"--and
  238. it's not, it's a "bar", so "foobar" will match.  You would have to do
  239. something like C</(?foo)...bar/> for that.   We say "like" because there's
  240. the case of your "bar" not having three characters before it.  You could
  241. cover that this way: C</(?:(?!foo)...|^..?)bar/>.  Sometimes it's still
  242. easier just to say:
  243.  
  244.     if (/foo/ && $` =~ /bar$/)
  245.  
  246.  
  247. =item (?imsx)
  248.  
  249. One or more embedded pattern-match modifiers.  This is particularly
  250. useful for patterns that are specified in a table somewhere, some of
  251. which want to be case sensitive, and some of which don't.  The case
  252. insensitive ones merely need to include C<(?i)> at the front of the
  253. pattern.  For example:
  254.  
  255.     $pattern = "foobar";
  256.     if ( /$pattern/i )
  257.  
  258.     # more flexible:
  259.  
  260.     $pattern = "(?i)foobar";
  261.     if ( /$pattern/ )
  262.  
  263. =back
  264.  
  265. The specific choice of question mark for this and the new minimal
  266. matching construct was because 1) question mark is pretty rare in older
  267. regular expressions, and 2) whenever you see one, you should stop
  268. and "question" exactly what is going on.  That's psychology...
  269.  
  270. =head2 Backtracking
  271.  
  272. A fundamental feature of regular expression matching involves the notion
  273. called I<backtracking>.  which is used (when needed) by all regular
  274. expression quantifiers, namely C<*>, C<*?>, C<+>, C<+?>, C<{n,m}>, and
  275. C<{n,m}?>.
  276.  
  277. For a regular expression to match, the I<entire> regular expression must
  278. match, not just part of it.  So if the beginning of a pattern containing a
  279. quantifier succeeds in a way that causes later parts in the pattern to
  280. fail, the matching engine backs up and recalculates the beginning
  281. part--that's why it's called backtracking.
  282.  
  283. Here is an example of backtracking:  Let's say you want to find the
  284. word following "foo" in the string "Food is on the foo table.":
  285.  
  286.     $_ = "Food is on the foo table.";
  287.     if ( /\b(foo)\s+(\w+)/i ) {
  288.     print "$2 follows $1.\n";
  289.     }
  290.  
  291. When the match runs, the first part of the regular expression (C<\b(foo)>)
  292. finds a possible match right at the beginning of the string, and loads up
  293. $1 with "Foo".  However, as soon as the matching engine sees that there's
  294. no whitespace following the "Foo" that it had saved in $1, it realizes its
  295. mistake and starts over again one character after where it had had the
  296. tentative match.  This time it goes all the way until the next occurrence
  297. of "foo". The complete regular expression matches this time, and you get
  298. the expected output of "table follows foo."
  299.  
  300. Sometimes minimal matching can help a lot.  Imagine you'd like to match
  301. everything between "foo" and "bar".  Initially, you write something
  302. like this:
  303.  
  304.     $_ =  "The food is under the bar in the barn.";
  305.     if ( /foo(.*)bar/ ) {
  306.     print "got <$1>\n";
  307.     }
  308.  
  309. Which perhaps unexpectedly yields:
  310.  
  311.   got <d is under the bar in the >
  312.  
  313. That's because C<.*> was greedy, so you get everything between the
  314. I<first> "foo" and the I<last> "bar".  In this case, it's more effective
  315. to use minimal matching to make sure you get the text between a "foo"
  316. and the first "bar" thereafter.
  317.  
  318.     if ( /foo(.*?)bar/ ) { print "got <$1>\n" }
  319.   got <d is under the >
  320.  
  321. Here's another example: let's say you'd like to match a number at the end
  322. of a string, and you also want to keep the preceding part the match.
  323. So you write this:
  324.  
  325.     $_ = "I have 2 numbers: 53147";
  326.     if ( /(.*)(\d*)/ ) {                # Wrong!
  327.     print "Beginning is <$1>, number is <$2>.\n";
  328.     }
  329.  
  330. That won't work at all, because C<.*> was greedy and gobbled up the
  331. whole string. As C<\d*> can match on an empty string the complete
  332. regular expression matched successfully.
  333.  
  334.     Beginning is <I have 2: 53147>, number is <>.
  335.  
  336. Here are some variants, most of which don't work:
  337.  
  338.     $_ = "I have 2 numbers: 53147";
  339.     @pats = qw{
  340.     (.*)(\d*)
  341.     (.*)(\d+)
  342.     (.*?)(\d*)
  343.     (.*?)(\d+)
  344.     (.*)(\d+)$
  345.     (.*?)(\d+)$
  346.     (.*)\b(\d+)$
  347.     (.*\D)(\d+)$
  348.     };
  349.  
  350.     for $pat (@pats) {
  351.     printf "%-12s ", $pat;
  352.     if ( /$pat/ ) {
  353.         print "<$1> <$2>\n";
  354.     } else {
  355.         print "FAIL\n";
  356.     }
  357.     }
  358.  
  359. That will print out:
  360.  
  361.     (.*)(\d*)    <I have 2 numbers: 53147> <>
  362.     (.*)(\d+)    <I have 2 numbers: 5314> <7>
  363.     (.*?)(\d*)   <> <>
  364.     (.*?)(\d+)   <I have > <2>
  365.     (.*)(\d+)$   <I have 2 numbers: 5314> <7>
  366.     (.*?)(\d+)$  <I have 2 numbers: > <53147>
  367.     (.*)\b(\d+)$ <I have 2 numbers: > <53147>
  368.     (.*\D)(\d+)$ <I have 2 numbers: > <53147>
  369.  
  370. As you see, this can be a bit tricky.  It's important to realize that a
  371. regular expression is merely a set of assertions that gives a definition
  372. of success.  There may be 0, 1, or several different ways that the
  373. definition might succeed against a particular string.  And if there are
  374. multiple ways it might succeed, you need to understand backtracking in
  375. order to know which variety of success you will achieve.
  376.  
  377. When using lookahead assertions and negations, this can all get even
  378. tricker.  Imagine you'd like to find a sequence of nondigits not 
  379. followed by "123".  You might try to write that as
  380.  
  381.     $_ = "ABC123";
  382.     if ( /^\D*(?!123)/ ) {                # Wrong!
  383.         print "Yup, no 123 in $_\n";
  384.     }
  385.  
  386. But that isn't going to match; at least, not the way you're hoping.  It
  387. claims that there is no 123 in the string.  Here's a clearer picture of
  388. why it that pattern matches, contrary to popular expectations:
  389.  
  390.     $x = 'ABC123' ;
  391.     $y = 'ABC445' ;
  392.  
  393.     print "1: got $1\n" if $x =~ /^(ABC)(?!123)/ ;
  394.     print "2: got $1\n" if $y =~ /^(ABC)(?!123)/ ;
  395.  
  396.     print "3: got $1\n" if $x =~ /^(\D*)(?!123)/ ;
  397.     print "4: got $1\n" if $y =~ /^(\D*)(?!123)/ ;
  398.  
  399. This prints
  400.  
  401.     2: got ABC
  402.     3: got AB
  403.     4: got ABC
  404.  
  405. You might have expected test 3 to fail because it just seems to a more
  406. general purpose version of test 1.  The important difference between
  407. them is that test 3 contains a quantifier (C<\D*>) and so can use
  408. backtracking, whereas test 1 will not.  What's happening is
  409. that you've asked "Is it true that at the start of $x, following 0 or more
  410. nondigits, you have something that's not 123?"  If the pattern matcher had
  411. let C<\D*> expand to "ABC", this would have caused the whole pattern to
  412. fail.  
  413. The search engine will initially match C<\D*> with "ABC".  Then it will
  414. try to match C<(?!123> with "123" which, of course, fails.  But because
  415. a quantifier (C<\D*>) has been used in the regular expression, the
  416. search engine can backtrack and retry the match differently
  417. in the hope of matching the complete regular expression.  
  418.  
  419. Well now, 
  420. the pattern really, I<really> wants to succeed, so it uses the
  421. standard regexp backoff-and-retry and lets C<\D*> expand to just "AB" this
  422. time.  Now there's indeed something following "AB" that is not
  423. "123".  It's in fact "C123", which suffices.
  424.  
  425. We can deal with this by using both an assertion and a negation.  We'll
  426. say that the first part in $1 must be followed by a digit, and in fact, it
  427. must also be followed by something that's not "123".  Remember that the
  428. lookaheads are zero-width expressions--they only look, but don't consume
  429. any of the string in their match.  So rewriting this way produces what
  430. you'd expect; that is, case 5 will fail, but case 6 succeeds:
  431.  
  432.     print "5: got $1\n" if $x =~ /^(\D*)(?=\d)(?!123)/ ;
  433.     print "6: got $1\n" if $y =~ /^(\D*)(?=\d)(?!123)/ ;
  434.  
  435.     6: got ABC
  436.  
  437. In other words, the two zero-width assertions next to each other work like
  438. they're ANDed together, just as you'd use any builtin assertions:  C</^$/>
  439. matches only if you're at the beginning of the line AND the end of the
  440. line simultaneously.  The deeper underlying truth is that juxtaposition in
  441. regular expressions always means AND, except when you write an explicit OR
  442. using the vertical bar.  C</ab/> means match "a" AND (then) match "b",
  443. although the attempted matches are made at different positions because "a"
  444. is not a zero-width assertion, but a one-width assertion.
  445.  
  446. One warning: particularly complicated regular expressions can take
  447. exponential time to solve due to the immense number of possible ways they
  448. can use backtracking to try match.  For example this will take a very long
  449. time to run
  450.  
  451.     /((a{0,5}){0,5}){0,5}/
  452.  
  453. And if you used C<*>'s instead of limiting it to 0 through 5 matches, then
  454. it would take literally forever--or until you ran out of stack space.
  455.  
  456. =head2 Version 8 Regular Expressions
  457.  
  458. In case you're not familiar with the "regular" Version 8 regexp
  459. routines, here are the pattern-matching rules not described above.
  460.  
  461. Any single character matches itself, unless it is a I<metacharacter>
  462. with a special meaning described here or above.  You can cause
  463. characters which normally function as metacharacters to be interpreted
  464. literally by prefixing them with a "\" (e.g. "\." matches a ".", not any
  465. character; "\\" matches a "\").  A series of characters matches that
  466. series of characters in the target string, so the pattern C<blurfl>
  467. would match "blurfl" in the target string.
  468.  
  469. You can specify a character class, by enclosing a list of characters
  470. in C<[]>, which will match any one of the characters in the list.  If the
  471. first character after the "[" is "^", the class matches any character not
  472. in the list.  Within a list, the "-" character is used to specify a
  473. range, so that C<a-z> represents all the characters between "a" and "z",
  474. inclusive.
  475.  
  476. Characters may be specified using a metacharacter syntax much like that
  477. used in C: "\n" matches a newline, "\t" a tab, "\r" a carriage return,
  478. "\f" a form feed, etc.  More generally, \I<nnn>, where I<nnn> is a string
  479. of octal digits, matches the character whose ASCII value is I<nnn>.
  480. Similarly, \xI<nn>, where I<nn> are hexidecimal digits, matches the
  481. character whose ASCII value is I<nn>. The expression \cI<x> matches the
  482. ASCII character control-I<x>.  Finally, the "." metacharacter matches any
  483. character except "\n" (unless you use C</s>).
  484.  
  485. You can specify a series of alternatives for a pattern using "|" to
  486. separate them, so that C<fee|fie|foe> will match any of "fee", "fie",
  487. or "foe" in the target string (as would C<f(e|i|o)e>).  Note that the
  488. first alternative includes everything from the last pattern delimiter
  489. ("(", "[", or the beginning of the pattern) up to the first "|", and
  490. the last alternative contains everything from the last "|" to the next
  491. pattern delimiter.  For this reason, it's common practice to include
  492. alternatives in parentheses, to minimize confusion about where they
  493. start and end.  Note however that "|" is interpreted as a literal with
  494. square brackets, so if you write C<[fee|fie|foe]> you're really only
  495. matching C<[feio|]>.
  496.  
  497. Within a pattern, you may designate subpatterns for later reference by
  498. enclosing them in parentheses, and you may refer back to the I<n>th
  499. subpattern later in the pattern using the metacharacter \I<n>.
  500. Subpatterns are numbered based on the left to right order of their
  501. opening parenthesis.  Note that a backreference matches whatever
  502. actually matched the subpattern in the string being examined, not the
  503. rules for that subpattern.  Therefore, C<(0|0x)\d*\s\1\d*> will
  504. match "0x1234 0x4321",but not "0x1234 01234", since subpattern 1
  505. actually matched "0x", even though the rule C<0|0x> could
  506. potentially match the leading 0 in the second number.
  507.  
  508. =head2 WARNING on \1 vs $1
  509.  
  510. Some people get too used to writing things like
  511.  
  512.     $pattern =~ s/(\W)/\\\1/g;
  513.  
  514. This is grandfathered for the RHS of a substitute to avoid shocking the
  515. B<sed> addicts, but it's a dirty habit to get into.  That's because in
  516. PerlThink, the right-hand side of a C<s///> is a double-quoted string.  C<\1> in
  517. the usual double-quoted string means a control-A.  The customary Unix
  518. meaning of C<\1> is kludged in for C<s///>.  However, if you get into the habit
  519. of doing that, you get yourself into trouble if you then add an C</e>
  520. modifier.
  521.  
  522.     s/(\d+)/ \1 + 1 /eg;
  523.  
  524. Or if you try to do
  525.  
  526.     s/(\d+)/\1000/;
  527.  
  528. You can't disambiguate that by saying C<\{1}000>, whereas you can fix it with
  529. C<${1}000>.  Basically, the operation of interpolation should not be confused
  530. with the operation of matching a backreference.  Certainly they mean two
  531. different things on the I<left> side of the C<s///>.
  532.