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