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