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