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