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