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