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