This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Minor cleanup of RE tests 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
75e14d17 9operations, plus various examples of the same, see discussion
1e66bd83 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
1e66bd83
PP
14are listed below. For the modifiers that alter the way a regular expression
15is used by Perl, see L<perlop/"Regexp Quote-Like Operators"> and
16L<perlop/"Gory details of parsing quoted constructs">.
a0d0e21e 17
55497cff
PP
18=over 4
19
20=item i
21
22Do case-insensitive pattern matching.
23
a034a98d
DD
24If C<use locale> is in effect, the case map is taken from the current
25locale. See L<perllocale>.
26
54310121 27=item m
55497cff
PP
28
29Treat string as multiple lines. That is, change "^" and "$" from matching
5f05dabc 30at only the very start or end of the string to the start or end of any
55497cff
PP
31line anywhere within the string,
32
54310121 33=item s
55497cff
PP
34
35Treat string as single line. That is, change "." to match any character
36whatsoever, even a newline, which it normally would not match.
37
5a964f20
TC
38The C</s> and C</m> modifiers both override the C<$*> setting. That is, no matter
39what C<$*> contains, C</s> without C</m> will force "^" to match only at the
7b8d334a
GS
40beginning of the string and "$" to match only at the end (or just before a
41newline at the end) of the string. Together, as /ms, they let the "." match
42any character whatsoever, while yet allowing "^" and "$" to match,
43respectively, just after and just before newlines within the string.
44
54310121 45=item x
55497cff
PP
46
47Extend your pattern's legibility by permitting whitespace and comments.
48
49=back
a0d0e21e
LW
50
51These are usually written as "the C</x> modifier", even though the delimiter
52in question might not actually be a slash. In fact, any of these
53modifiers may also be embedded within the regular expression itself using
54the new C<(?...)> construct. See below.
55
4633a7c4 56The C</x> modifier itself needs a little more explanation. It tells
55497cff
PP
57the regular expression parser to ignore whitespace that is neither
58backslashed nor within a character class. You can use this to break up
4633a7c4 59your regular expression into (slightly) more readable parts. The C<#>
54310121 60character is also treated as a metacharacter introducing a comment,
55497cff 61just as in ordinary Perl code. This also means that if you want real
5a964f20
TC
62whitespace or C<#> characters in the pattern (outside of a character
63class, where they are unaffected by C</x>), that you'll either have to
55497cff
PP
64escape them or encode them using octal or hex escapes. Taken together,
65these features go a long way towards making Perl's regular expressions
0c815be9
HS
66more readable. Note that you have to be careful not to include the
67pattern delimiter in the comment--perl has no way of knowing you did
5a964f20 68not intend to close the pattern early. See the C-comment deletion code
0c815be9 69in L<perlop>.
a0d0e21e
LW
70
71=head2 Regular Expressions
72
73The patterns used in pattern matching are regular expressions such as
5a964f20 74those supplied in the Version 8 regex routines. (In fact, the
a0d0e21e
LW
75routines are derived (distantly) from Henry Spencer's freely
76redistributable reimplementation of the V8 routines.)
77See L<Version 8 Regular Expressions> for details.
78
79In particular the following metacharacters have their standard I<egrep>-ish
80meanings:
81
54310121 82 \ Quote the next metacharacter
a0d0e21e
LW
83 ^ Match the beginning of the line
84 . Match any character (except newline)
c07a80fd 85 $ Match the end of the line (or before newline at the end)
a0d0e21e
LW
86 | Alternation
87 () Grouping
88 [] Character class
89
5f05dabc
PP
90By default, the "^" character is guaranteed to match at only the
91beginning of the string, the "$" character at only the end (or before the
a0d0e21e
LW
92newline at the end) and Perl does certain optimizations with the
93assumption that the string contains only one line. Embedded newlines
94will not be matched by "^" or "$". You may, however, wish to treat a
4a6725af 95string as a multi-line buffer, such that the "^" will match after any
a0d0e21e
LW
96newline within the string, and "$" will match before any newline. At the
97cost of a little more overhead, you can do this by using the /m modifier
98on the pattern match operator. (Older programs did this by setting C<$*>,
5f05dabc 99but this practice is now deprecated.)
a0d0e21e 100
4a6725af 101To facilitate multi-line substitutions, the "." character never matches a
55497cff 102newline unless you use the C</s> modifier, which in effect tells Perl to pretend
a0d0e21e
LW
103the string is a single line--even if it isn't. The C</s> modifier also
104overrides the setting of C<$*>, in case you have some (badly behaved) older
105code that sets it in another module.
106
107The following standard quantifiers are recognized:
108
109 * Match 0 or more times
110 + Match 1 or more times
111 ? Match 1 or 0 times
112 {n} Match exactly n times
113 {n,} Match at least n times
114 {n,m} Match at least n but not more than m times
115
116(If a curly bracket occurs in any other context, it is treated
117as a regular character.) The "*" modifier is equivalent to C<{0,}>, the "+"
25f94b33 118modifier to C<{1,}>, and the "?" modifier to C<{0,1}>. n and m are limited
c07a80fd 119to integral values less than 65536.
a0d0e21e 120
54310121
PP
121By default, a quantified subpattern is "greedy", that is, it will match as
122many times as possible (given a particular starting location) while still
123allowing the rest of the pattern to match. If you want it to match the
124minimum number of times possible, follow the quantifier with a "?". Note
125that the meanings don't change, just the "greediness":
a0d0e21e
LW
126
127 *? Match 0 or more times
128 +? Match 1 or more times
129 ?? Match 0 or 1 time
130 {n}? Match exactly n times
131 {n,}? Match at least n times
132 {n,m}? Match at least n but not more than m times
133
5f05dabc 134Because patterns are processed as double quoted strings, the following
a0d0e21e
LW
135also work:
136
0f36ee90
PP
137 \t tab (HT, TAB)
138 \n newline (LF, NL)
139 \r return (CR)
140 \f form feed (FF)
141 \a alarm (bell) (BEL)
142 \e escape (think troff) (ESC)
cb1a09d0
AD
143 \033 octal char (think of a PDP-11)
144 \x1B hex char
a0d0e21e 145 \c[ control char
cb1a09d0
AD
146 \l lowercase next char (think vi)
147 \u uppercase next char (think vi)
148 \L lowercase till \E (think vi)
149 \U uppercase till \E (think vi)
150 \E end case modification (think vi)
5a964f20 151 \Q quote (disable) pattern metacharacters till \E
a0d0e21e 152
a034a98d 153If C<use locale> is in effect, the case map used by C<\l>, C<\L>, C<\u>
7b8d334a 154and C<\U> is taken from the current locale. See L<perllocale>.
a034a98d 155
1d2dff63
GS
156You cannot include a literal C<$> or C<@> within a C<\Q> sequence.
157An unescaped C<$> or C<@> interpolates the corresponding variable,
158while escaping will cause the literal string C<\$> to be matched.
159You'll need to write something like C<m/\Quser\E\@\Qhost/>.
160
a0d0e21e
LW
161In addition, Perl defines the following:
162
163 \w Match a "word" character (alphanumeric plus "_")
164 \W Match a non-word character
165 \s Match a whitespace character
166 \S Match a non-whitespace character
167 \d Match a digit character
168 \D Match a non-digit character
169
5a964f20 170A C<\w> matches a single alphanumeric character, not a whole
a034a98d
DD
171word. To match a word you'd need to say C<\w+>. If C<use locale> is in
172effect, the list of alphabetic characters generated by C<\w> is taken
173from the current locale. See L<perllocale>. You may use C<\w>, C<\W>,
174C<\s>, C<\S>, C<\d>, and C<\D> within character classes (though not as
175either end of a range).
a0d0e21e
LW
176
177Perl defines the following zero-width assertions:
178
179 \b Match a word boundary
180 \B Match a non-(word boundary)
b85d18e9
IZ
181 \A Match only at beginning of string
182 \Z Match only at end of string, or before newline at the end
183 \z Match only at end of string
a99df21c 184 \G Match only where previous m//g left off (works only with /g)
a0d0e21e
LW
185
186A word boundary (C<\b>) is defined as a spot between two characters that
68dc0745 187has a C<\w> on one side of it and a C<\W> on the other side of it (in
a0d0e21e
LW
188either order), counting the imaginary characters off the beginning and
189end of the string as matching a C<\W>. (Within character classes C<\b>
190represents backspace rather than a word boundary.) The C<\A> and C<\Z> are
5a964f20 191just like "^" and "$", except that they won't match multiple times when the
a0d0e21e 192C</m> modifier is used, while "^" and "$" will match at every internal line
c07a80fd 193boundary. To match the actual end of the string, not ignoring newline,
b85d18e9 194you can use C<\z>. The C<\G> assertion can be used to chain global
a99df21c 195matches (using C<m//g>), as described in
e7ea3e70 196L<perlop/"Regexp Quote-Like Operators">.
a99df21c 197
e7ea3e70 198It is also useful when writing C<lex>-like scanners, when you have several
5a964f20 199patterns that you want to match against consequent substrings of your
e7ea3e70 200string, see the previous reference.
44a8e56a
PP
201The actual location where C<\G> will match can also be influenced
202by using C<pos()> as an lvalue. See L<perlfunc/pos>.
a0d0e21e 203
0f36ee90 204When the bracketing construct C<( ... )> is used, \E<lt>digitE<gt> matches the
cb1a09d0 205digit'th substring. Outside of the pattern, always use "$" instead of "\"
0f36ee90 206in front of the digit. (While the \E<lt>digitE<gt> notation can on rare occasion work
cb1a09d0 207outside the current pattern, this should not be relied upon. See the
0f36ee90 208WARNING below.) The scope of $E<lt>digitE<gt> (and C<$`>, C<$&>, and C<$'>)
cb1a09d0
AD
209extends to the end of the enclosing BLOCK or eval string, or to the next
210successful pattern match, whichever comes first. If you want to use
5f05dabc 211parentheses to delimit a subpattern (e.g., a set of alternatives) without
84dc3c4d 212saving it as a subpattern, follow the ( with a ?:.
cb1a09d0
AD
213
214You may have as many parentheses as you wish. If you have more
a0d0e21e
LW
215than 9 substrings, the variables $10, $11, ... refer to the
216corresponding substring. Within the pattern, \10, \11, etc. refer back
5f05dabc 217to substrings if there have been at least that many left parentheses before
c07a80fd 218the backreference. Otherwise (for backward compatibility) \10 is the
a0d0e21e
LW
219same as \010, a backspace, and \11 the same as \011, a tab. And so
220on. (\1 through \9 are always backreferences.)
221
222C<$+> returns whatever the last bracket match matched. C<$&> returns the
0f36ee90 223entire matched string. (C<$0> used to return the same thing, but not any
a0d0e21e
LW
224more.) C<$`> returns everything before the matched string. C<$'> returns
225everything after the matched string. Examples:
226
227 s/^([^ ]*) *([^ ]*)/$2 $1/; # swap first two words
228
229 if (/Time: (..):(..):(..)/) {
230 $hours = $1;
231 $minutes = $2;
232 $seconds = $3;
233 }
234
68dc0745
PP
235Once perl sees that you need one of C<$&>, C<$`> or C<$'> anywhere in
236the program, it has to provide them on each and every pattern match.
237This can slow your program down. The same mechanism that handles
238these provides for the use of $1, $2, etc., so you pay the same price
5a964f20
TC
239for each pattern that contains capturing parentheses. But if you never
240use $&, etc., in your script, then patterns I<without> capturing
68dc0745
PP
241parentheses won't be penalized. So avoid $&, $', and $` if you can,
242but if you can't (and some algorithms really appreciate them), once
243you've used them once, use them at will, because you've already paid
5a964f20 244the price. As of 5.005, $& is not so costly as the other two.
68dc0745 245
5a964f20 246Backslashed metacharacters in Perl are
201ecf35
AL
247alphanumeric, such as C<\b>, C<\w>, C<\n>. Unlike some other regular
248expression languages, there are no backslashed symbols that aren't
249alphanumeric. So anything that looks like \\, \(, \), \E<lt>, \E<gt>,
250\{, or \} is always interpreted as a literal character, not a
251metacharacter. This was once used in a common idiom to disable or
252quote the special meanings of regular expression metacharacters in a
5a964f20 253string that you want to use for a pattern. Simply quote all
a0d0e21e
LW
254non-alphanumeric characters:
255
256 $pattern =~ s/(\W)/\\$1/g;
257
201ecf35 258Now it is much more common to see either the quotemeta() function or
7b8d334a 259the C<\Q> escape sequence used to disable all metacharacters' special
201ecf35 260meanings like this:
a0d0e21e
LW
261
262 /$unquoted\Q$quoted\E$unquoted/
263
5f05dabc
PP
264Perl defines a consistent extension syntax for regular expressions.
265The syntax is a pair of parentheses with a question mark as the first
266thing within the parentheses (this was a syntax error in older
267versions of Perl). The character after the question mark gives the
268function of the extension. Several extensions are already supported:
a0d0e21e
LW
269
270=over 10
271
cc6b7395 272=item C<(?#text)>
a0d0e21e 273
cb1a09d0 274A comment. The text is ignored. If the C</x> switch is used to enable
259138e3
GS
275whitespace formatting, a simple C<#> will suffice. Note that perl closes
276the comment as soon as it sees a C<)>, so there is no way to put a literal
277C<)> in the comment.
a0d0e21e 278
5a964f20 279=item C<(?:pattern)>
a0d0e21e 280
ca9dfc88
IZ
281=item C<(?imsx-imsx:pattern)>
282
5a964f20
TC
283This is for clustering, not capturing; it groups subexpressions like
284"()", but doesn't make backreferences as "()" does. So
a0d0e21e 285
5a964f20 286 @fields = split(/\b(?:a|b|c)\b/)
a0d0e21e
LW
287
288is like
289
5a964f20 290 @fields = split(/\b(a|b|c)\b/)
a0d0e21e
LW
291
292but doesn't spit out extra fields.
293
ca9dfc88
IZ
294The letters between C<?> and C<:> act as flags modifiers, see
295L<C<(?imsx-imsx)>>. In particular,
296
297 /(?s-i:more.*than).*million/i
298
299is equivalent to more verbose
300
301 /(?:(?s-i)more.*than).*million/i
302
5a964f20 303=item C<(?=pattern)>
a0d0e21e
LW
304
305A zero-width positive lookahead assertion. For example, C</\w+(?=\t)/>
306matches a word followed by a tab, without including the tab in C<$&>.
307
5a964f20 308=item C<(?!pattern)>
a0d0e21e
LW
309
310A zero-width negative lookahead assertion. For example C</foo(?!bar)/>
311matches any occurrence of "foo" that isn't followed by "bar". Note
312however that lookahead and lookbehind are NOT the same thing. You cannot
7b8d334a
GS
313use this for lookbehind.
314
5a964f20 315If you are looking for a "bar" that isn't preceded by a "foo", C</(?!foo)bar/>
7b8d334a
GS
316will not do what you want. That's because the C<(?!foo)> is just saying that
317the next thing cannot be "foo"--and it's not, it's a "bar", so "foobar" will
318match. You would have to do something like C</(?!foo)...bar/> for that. We
319say "like" because there's the case of your "bar" not having three characters
320before it. You could cover that this way: C</(?:(?!foo)...|^.{0,2})bar/>.
321Sometimes it's still easier just to say:
a0d0e21e 322
a3cb178b 323 if (/bar/ && $` !~ /foo$/)
a0d0e21e 324
c277df42
IZ
325For lookbehind see below.
326
5a964f20 327=item C<(?E<lt>=pattern)>
c277df42 328
5a964f20 329A zero-width positive lookbehind assertion. For example, C</(?E<lt>=\t)\w+/>
c277df42
IZ
330matches a word following a tab, without including the tab in C<$&>.
331Works only for fixed-width lookbehind.
332
5a964f20 333=item C<(?<!pattern)>
c277df42
IZ
334
335A zero-width negative lookbehind assertion. For example C</(?<!bar)foo/>
336matches any occurrence of "foo" that isn't following "bar".
337Works only for fixed-width lookbehind.
338
cc6b7395 339=item C<(?{ code })>
c277df42
IZ
340
341Experimental "evaluate any Perl code" zero-width assertion. Always
cc6b7395
IZ
342succeeds. C<code> is not interpolated. Currently the rules to
343determine where the C<code> ends are somewhat convoluted.
c277df42 344
b9ac3b5b
GS
345The C<code> is properly scoped in the following sense: if the assertion
346is backtracked (compare L<"Backtracking">), all the changes introduced after
347C<local>isation are undone, so
348
349 $_ = 'a' x 8;
350 m<
351 (?{ $cnt = 0 }) # Initialize $cnt.
352 (
353 a
354 (?{
355 local $cnt = $cnt + 1; # Update $cnt, backtracking-safe.
356 })
357 )*
358 aaaa
359 (?{ $res = $cnt }) # On success copy to non-localized
360 # location.
361 >x;
362
363will set C<$res = 4>. Note that after the match $cnt returns to the globally
364introduced value 0, since the scopes which restrict C<local> statements
365are unwound.
366
367This assertion may be used as L<C<(?(condition)yes-pattern|no-pattern)>>
368switch. If I<not> used in this way, the result of evaluation of C<code>
369is put into variable $^R. This happens immediately, so $^R can be used from
370other C<(?{ code })> assertions inside the same regular expression.
371
372The above assignment to $^R is properly localized, thus the old value of $^R
373is restored if the assertion is backtracked (compare L<"Backtracking">).
374
871b0233
IZ
375Due to security concerns, this construction is not allowed if the regular
376expression involves run-time interpolation of variables, unless
377C<use re 'eval'> pragma is used (see L<re>), or the variables contain
378results of qr() operator (see L<perlop/"qr/STRING/imosx">).
379
380This restriction is due to the wide-spread (questionable) practice of
381using the construct
382
383 $re = <>;
384 chomp $re;
385 $string =~ /$re/;
386
387without tainting. While this code is frowned upon from security point
388of view, when C<(?{})> was introduced, it was considered bad to add
389I<new> security holes to existing scripts.
390
391B<NOTE:> Use of the above insecure snippet without also enabling taint mode
392is to be severely frowned upon. C<use re 'eval'> does not disable tainting
393checks, thus to allow $re in the above snippet to contain C<(?{})>
394I<with tainting enabled>, one needs both C<use re 'eval'> and untaint
395the $re.
396
5a964f20
TC
397=item C<(?E<gt>pattern)>
398
399An "independent" subexpression. Matches the substring that a
400I<standalone> C<pattern> would match if anchored at the given position,
c277df42
IZ
401B<and only this substring>.
402
403Say, C<^(?E<gt>a*)ab> will never match, since C<(?E<gt>a*)> (anchored
5a964f20 404at the beginning of string, as above) will match I<all> characters
c277df42
IZ
405C<a> at the beginning of string, leaving no C<a> for C<ab> to match.
406In contrast, C<a*ab> will match the same as C<a+b>, since the match of
407the subgroup C<a*> is influenced by the following group C<ab> (see
408L<"Backtracking">). In particular, C<a*> inside C<a*ab> will match
aca73f04 409fewer characters than a standalone C<a*>, since this makes the tail match.
c277df42 410
5a964f20 411An effect similar to C<(?E<gt>pattern)> may be achieved by
c277df42 412
5a964f20 413 (?=(pattern))\1
c277df42
IZ
414
415since the lookahead is in I<"logical"> context, thus matches the same
416substring as a standalone C<a+>. The following C<\1> eats the matched
417string, thus making a zero-length assertion into an analogue of
871b0233 418C<(?E<gt>...)>. (The difference between these two constructs is that the
5a964f20 419second one uses a catching group, thus shifting ordinals of
c277df42
IZ
420backreferences in the rest of a regular expression.)
421
5a964f20
TC
422This construct is useful for optimizations of "eternal"
423matches, because it will not backtrack (see L<"Backtracking">).
c277df42 424
871b0233
IZ
425 m{ \(
426 (
427 [^()]+
428 |
429 \( [^()]* \)
430 )+
431 \)
432 }x
5a964f20
TC
433
434That will efficiently match a nonempty group with matching
435two-or-less-level-deep parentheses. However, if there is no such group,
436it will take virtually forever on a long string. That's because there are
437so many different ways to split a long string into several substrings.
871b0233
IZ
438This is what C<(.+)+> is doing, and C<(.+)+> is similar to a subpattern
439of the above pattern. Consider that the above pattern detects no-match
440on C<((()aaaaaaaaaaaaaaaaaa> in several seconds, but that each extra
5a964f20
TC
441letter doubles this time. This exponential performance will make it
442appear that your program has hung.
443
444However, a tiny modification of this pattern
445
871b0233
IZ
446 m{ \(
447 (
448 (?> [^()]+ )
449 |
450 \( [^()]* \)
451 )+
452 \)
453 }x
c277df42 454
5a964f20
TC
455which uses C<(?E<gt>...)> matches exactly when the one above does (verifying
456this yourself would be a productive exercise), but finishes in a fourth
457the time when used on a similar string with 1000000 C<a>s. Be aware,
458however, that this pattern currently triggers a warning message under
459B<-w> saying it C<"matches the null string many times">):
c277df42 460
5a964f20 461On simple groups, such as the pattern C<(?> [^()]+ )>, a comparable
c277df42
IZ
462effect may be achieved by negative lookahead, as in C<[^()]+ (?! [^()] )>.
463This was only 4 times slower on a string with 1000000 C<a>s.
464
5a964f20 465=item C<(?(condition)yes-pattern|no-pattern)>
c277df42 466
5a964f20 467=item C<(?(condition)yes-pattern)>
c277df42
IZ
468
469Conditional expression. C<(condition)> should be either an integer in
470parentheses (which is valid if the corresponding pair of parentheses
471matched), or lookahead/lookbehind/evaluate zero-width assertion.
472
473Say,
474
5a964f20 475 m{ ( \( )?
871b0233 476 [^()]+
5a964f20 477 (?(1) \) )
871b0233 478 }x
c277df42
IZ
479
480matches a chunk of non-parentheses, possibly included in parentheses
481themselves.
a0d0e21e 482
ca9dfc88 483=item C<(?imsx-imsx)>
a0d0e21e
LW
484
485One or more embedded pattern-match modifiers. This is particularly
486useful for patterns that are specified in a table somewhere, some of
487which want to be case sensitive, and some of which don't. The case
5f05dabc 488insensitive ones need to include merely C<(?i)> at the front of the
a0d0e21e
LW
489pattern. For example:
490
491 $pattern = "foobar";
5a964f20 492 if ( /$pattern/i ) { }
a0d0e21e
LW
493
494 # more flexible:
495
496 $pattern = "(?i)foobar";
5a964f20 497 if ( /$pattern/ ) { }
a0d0e21e 498
ca9dfc88
IZ
499Letters after C<-> switch modifiers off.
500
5a964f20 501These modifiers are localized inside an enclosing group (if any). Say,
c277df42
IZ
502
503 ( (?i) blah ) \s+ \1
504
505(assuming C<x> modifier, and no C<i> modifier outside of this group)
506will match a repeated (I<including the case>!) word C<blah> in any
507case.
508
a0d0e21e
LW
509=back
510
5a964f20
TC
511A question mark was chosen for this and for the new minimal-matching
512construct because 1) question mark is pretty rare in older regular
513expressions, and 2) whenever you see one, you should stop and "question"
514exactly what is going on. That's psychology...
a0d0e21e 515
c07a80fd
PP
516=head2 Backtracking
517
c277df42 518A fundamental feature of regular expression matching involves the
5a964f20 519notion called I<backtracking>, which is currently used (when needed)
c277df42
IZ
520by all regular expression quantifiers, namely C<*>, C<*?>, C<+>,
521C<+?>, C<{n,m}>, and C<{n,m}?>.
c07a80fd
PP
522
523For a regular expression to match, the I<entire> regular expression must
524match, not just part of it. So if the beginning of a pattern containing a
525quantifier succeeds in a way that causes later parts in the pattern to
526fail, the matching engine backs up and recalculates the beginning
527part--that's why it's called backtracking.
528
529Here is an example of backtracking: Let's say you want to find the
530word following "foo" in the string "Food is on the foo table.":
531
532 $_ = "Food is on the foo table.";
533 if ( /\b(foo)\s+(\w+)/i ) {
534 print "$2 follows $1.\n";
535 }
536
537When the match runs, the first part of the regular expression (C<\b(foo)>)
538finds a possible match right at the beginning of the string, and loads up
539$1 with "Foo". However, as soon as the matching engine sees that there's
540no whitespace following the "Foo" that it had saved in $1, it realizes its
68dc0745 541mistake and starts over again one character after where it had the
c07a80fd
PP
542tentative match. This time it goes all the way until the next occurrence
543of "foo". The complete regular expression matches this time, and you get
544the expected output of "table follows foo."
545
546Sometimes minimal matching can help a lot. Imagine you'd like to match
547everything between "foo" and "bar". Initially, you write something
548like this:
549
550 $_ = "The food is under the bar in the barn.";
551 if ( /foo(.*)bar/ ) {
552 print "got <$1>\n";
553 }
554
555Which perhaps unexpectedly yields:
556
557 got <d is under the bar in the >
558
559That's because C<.*> was greedy, so you get everything between the
560I<first> "foo" and the I<last> "bar". In this case, it's more effective
561to use minimal matching to make sure you get the text between a "foo"
562and the first "bar" thereafter.
563
564 if ( /foo(.*?)bar/ ) { print "got <$1>\n" }
565 got <d is under the >
566
567Here's another example: let's say you'd like to match a number at the end
568of a string, and you also want to keep the preceding part the match.
569So you write this:
570
571 $_ = "I have 2 numbers: 53147";
572 if ( /(.*)(\d*)/ ) { # Wrong!
573 print "Beginning is <$1>, number is <$2>.\n";
574 }
575
576That won't work at all, because C<.*> was greedy and gobbled up the
577whole string. As C<\d*> can match on an empty string the complete
578regular expression matched successfully.
579
8e1088bc 580 Beginning is <I have 2 numbers: 53147>, number is <>.
c07a80fd
PP
581
582Here are some variants, most of which don't work:
583
584 $_ = "I have 2 numbers: 53147";
585 @pats = qw{
586 (.*)(\d*)
587 (.*)(\d+)
588 (.*?)(\d*)
589 (.*?)(\d+)
590 (.*)(\d+)$
591 (.*?)(\d+)$
592 (.*)\b(\d+)$
593 (.*\D)(\d+)$
594 };
595
596 for $pat (@pats) {
597 printf "%-12s ", $pat;
598 if ( /$pat/ ) {
599 print "<$1> <$2>\n";
600 } else {
601 print "FAIL\n";
602 }
603 }
604
605That will print out:
606
607 (.*)(\d*) <I have 2 numbers: 53147> <>
608 (.*)(\d+) <I have 2 numbers: 5314> <7>
609 (.*?)(\d*) <> <>
610 (.*?)(\d+) <I have > <2>
611 (.*)(\d+)$ <I have 2 numbers: 5314> <7>
612 (.*?)(\d+)$ <I have 2 numbers: > <53147>
613 (.*)\b(\d+)$ <I have 2 numbers: > <53147>
614 (.*\D)(\d+)$ <I have 2 numbers: > <53147>
615
616As you see, this can be a bit tricky. It's important to realize that a
617regular expression is merely a set of assertions that gives a definition
618of success. There may be 0, 1, or several different ways that the
619definition might succeed against a particular string. And if there are
5a964f20
TC
620multiple ways it might succeed, you need to understand backtracking to
621know which variety of success you will achieve.
c07a80fd
PP
622
623When using lookahead assertions and negations, this can all get even
54310121 624tricker. Imagine you'd like to find a sequence of non-digits not
c07a80fd
PP
625followed by "123". You might try to write that as
626
871b0233
IZ
627 $_ = "ABC123";
628 if ( /^\D*(?!123)/ ) { # Wrong!
629 print "Yup, no 123 in $_\n";
630 }
c07a80fd
PP
631
632But that isn't going to match; at least, not the way you're hoping. It
633claims that there is no 123 in the string. Here's a clearer picture of
634why it that pattern matches, contrary to popular expectations:
635
636 $x = 'ABC123' ;
637 $y = 'ABC445' ;
638
639 print "1: got $1\n" if $x =~ /^(ABC)(?!123)/ ;
640 print "2: got $1\n" if $y =~ /^(ABC)(?!123)/ ;
641
642 print "3: got $1\n" if $x =~ /^(\D*)(?!123)/ ;
643 print "4: got $1\n" if $y =~ /^(\D*)(?!123)/ ;
644
645This prints
646
647 2: got ABC
648 3: got AB
649 4: got ABC
650
5f05dabc 651You might have expected test 3 to fail because it seems to a more
c07a80fd
PP
652general purpose version of test 1. The important difference between
653them is that test 3 contains a quantifier (C<\D*>) and so can use
654backtracking, whereas test 1 will not. What's happening is
655that you've asked "Is it true that at the start of $x, following 0 or more
5f05dabc 656non-digits, you have something that's not 123?" If the pattern matcher had
c07a80fd 657let C<\D*> expand to "ABC", this would have caused the whole pattern to
54310121 658fail.
c07a80fd 659The search engine will initially match C<\D*> with "ABC". Then it will
5a964f20 660try to match C<(?!123> with "123", which of course fails. But because
c07a80fd
PP
661a quantifier (C<\D*>) has been used in the regular expression, the
662search engine can backtrack and retry the match differently
54310121 663in the hope of matching the complete regular expression.
c07a80fd 664
5a964f20
TC
665The pattern really, I<really> wants to succeed, so it uses the
666standard pattern back-off-and-retry and lets C<\D*> expand to just "AB" this
c07a80fd
PP
667time. Now there's indeed something following "AB" that is not
668"123". It's in fact "C123", which suffices.
669
670We can deal with this by using both an assertion and a negation. We'll
671say that the first part in $1 must be followed by a digit, and in fact, it
672must also be followed by something that's not "123". Remember that the
673lookaheads are zero-width expressions--they only look, but don't consume
674any of the string in their match. So rewriting this way produces what
675you'd expect; that is, case 5 will fail, but case 6 succeeds:
676
677 print "5: got $1\n" if $x =~ /^(\D*)(?=\d)(?!123)/ ;
678 print "6: got $1\n" if $y =~ /^(\D*)(?=\d)(?!123)/ ;
679
680 6: got ABC
681
5a964f20 682In other words, the two zero-width assertions next to each other work as though
c07a80fd
PP
683they're ANDed together, just as you'd use any builtin assertions: C</^$/>
684matches only if you're at the beginning of the line AND the end of the
685line simultaneously. The deeper underlying truth is that juxtaposition in
686regular expressions always means AND, except when you write an explicit OR
687using the vertical bar. C</ab/> means match "a" AND (then) match "b",
688although the attempted matches are made at different positions because "a"
689is not a zero-width assertion, but a one-width assertion.
690
691One warning: particularly complicated regular expressions can take
692exponential time to solve due to the immense number of possible ways they
693can use backtracking to try match. For example this will take a very long
694time to run
695
696 /((a{0,5}){0,5}){0,5}/
697
698And if you used C<*>'s instead of limiting it to 0 through 5 matches, then
699it would take literally forever--or until you ran out of stack space.
700
c277df42 701A powerful tool for optimizing such beasts is "independent" groups,
5a964f20 702which do not backtrace (see L<C<(?E<gt>pattern)>>). Note also that
c277df42
IZ
703zero-length lookahead/lookbehind assertions will not backtrace to make
704the tail match, since they are in "logical" context: only the fact
705whether they match or not is considered relevant. For an example
706where side-effects of a lookahead I<might> have influenced the
5a964f20 707following match, see L<C<(?E<gt>pattern)>>.
c277df42 708
a0d0e21e
LW
709=head2 Version 8 Regular Expressions
710
5a964f20 711In case you're not familiar with the "regular" Version 8 regex
a0d0e21e
LW
712routines, here are the pattern-matching rules not described above.
713
54310121 714Any single character matches itself, unless it is a I<metacharacter>
a0d0e21e 715with a special meaning described here or above. You can cause
5a964f20 716characters that normally function as metacharacters to be interpreted
5f05dabc 717literally by prefixing them with a "\" (e.g., "\." matches a ".", not any
a0d0e21e
LW
718character; "\\" matches a "\"). A series of characters matches that
719series of characters in the target string, so the pattern C<blurfl>
720would match "blurfl" in the target string.
721
722You can specify a character class, by enclosing a list of characters
5a964f20 723in C<[]>, which will match any one character from the list. If the
a0d0e21e
LW
724first character after the "[" is "^", the class matches any character not
725in the list. Within a list, the "-" character is used to specify a
5a964f20 726range, so that C<a-z> represents all characters between "a" and "z",
84850974
DD
727inclusive. If you want "-" itself to be a member of a class, put it
728at the start or end of the list, or escape it with a backslash. (The
729following all specify the same class of three characters: C<[-az]>,
730C<[az-]>, and C<[a\-z]>. All are different from C<[a-z]>, which
731specifies a class containing twenty-six characters.)
a0d0e21e 732
54310121 733Characters may be specified using a metacharacter syntax much like that
a0d0e21e
LW
734used in C: "\n" matches a newline, "\t" a tab, "\r" a carriage return,
735"\f" a form feed, etc. More generally, \I<nnn>, where I<nnn> is a string
736of octal digits, matches the character whose ASCII value is I<nnn>.
0f36ee90 737Similarly, \xI<nn>, where I<nn> are hexadecimal digits, matches the
a0d0e21e 738character whose ASCII value is I<nn>. The expression \cI<x> matches the
54310121 739ASCII character control-I<x>. Finally, the "." metacharacter matches any
a0d0e21e
LW
740character except "\n" (unless you use C</s>).
741
742You can specify a series of alternatives for a pattern using "|" to
743separate them, so that C<fee|fie|foe> will match any of "fee", "fie",
5a964f20 744or "foe" in the target string (as would C<f(e|i|o)e>). The
a0d0e21e
LW
745first alternative includes everything from the last pattern delimiter
746("(", "[", or the beginning of the pattern) up to the first "|", and
747the last alternative contains everything from the last "|" to the next
748pattern delimiter. For this reason, it's common practice to include
749alternatives in parentheses, to minimize confusion about where they
a3cb178b
GS
750start and end.
751
5a964f20 752Alternatives are tried from left to right, so the first
a3cb178b
GS
753alternative found for which the entire expression matches, is the one that
754is chosen. This means that alternatives are not necessarily greedy. For
755example: when mathing C<foo|foot> against "barefoot", only the "foo"
756part will match, as that is the first alternative tried, and it successfully
757matches the target string. (This might not seem important, but it is
758important when you are capturing matched text using parentheses.)
759
5a964f20 760Also remember that "|" is interpreted as a literal within square brackets,
a3cb178b 761so if you write C<[fee|fie|foe]> you're really only matching C<[feio|]>.
a0d0e21e 762
54310121 763Within a pattern, you may designate subpatterns for later reference by
a0d0e21e 764enclosing them in parentheses, and you may refer back to the I<n>th
54310121
PP
765subpattern later in the pattern using the metacharacter \I<n>.
766Subpatterns are numbered based on the left to right order of their
5a964f20 767opening parenthesis. A backreference matches whatever
54310121
PP
768actually matched the subpattern in the string being examined, not the
769rules for that subpattern. Therefore, C<(0|0x)\d*\s\1\d*> will
5a964f20 770match "0x1234 0x4321", but not "0x1234 01234", because subpattern 1
748a9306 771actually matched "0x", even though the rule C<0|0x> could
a0d0e21e 772potentially match the leading 0 in the second number.
cb1a09d0
AD
773
774=head2 WARNING on \1 vs $1
775
5a964f20 776Some people get too used to writing things like:
cb1a09d0
AD
777
778 $pattern =~ s/(\W)/\\\1/g;
779
780This is grandfathered for the RHS of a substitute to avoid shocking the
781B<sed> addicts, but it's a dirty habit to get into. That's because in
5f05dabc 782PerlThink, the righthand side of a C<s///> is a double-quoted string. C<\1> in
cb1a09d0
AD
783the usual double-quoted string means a control-A. The customary Unix
784meaning of C<\1> is kludged in for C<s///>. However, if you get into the habit
785of doing that, you get yourself into trouble if you then add an C</e>
786modifier.
787
5a964f20 788 s/(\d+)/ \1 + 1 /eg; # causes warning under -w
cb1a09d0
AD
789
790Or if you try to do
791
792 s/(\d+)/\1000/;
793
794You can't disambiguate that by saying C<\{1}000>, whereas you can fix it with
795C<${1}000>. Basically, the operation of interpolation should not be confused
796with the operation of matching a backreference. Certainly they mean two
797different things on the I<left> side of the C<s///>.
9fa51da4 798
c84d73f1
IZ
799=head2 Repeated patterns matching zero-length substring
800
801WARNING: Difficult material (and prose) ahead. This section needs a rewrite.
802
803Regular expressions provide a terse and powerful programming language. As
804with most other power tools, power comes together with the ability
805to wreak havoc.
806
807A common abuse of this power stems from the ability to make infinite
808loops using regular expressions, with something as innocous as:
809
810 'foo' =~ m{ ( o? )* }x;
811
812The C<o?> can match at the beginning of C<'foo'>, and since the position
813in the string is not moved by the match, C<o?> would match again and again
814due to the C<*> modifier. Another common way to create a similar cycle
815is with the looping modifier C<//g>:
816
817 @matches = ( 'foo' =~ m{ o? }xg );
818
819or
820
821 print "match: <$&>\n" while 'foo' =~ m{ o? }xg;
822
823or the loop implied by split().
824
825However, long experience has shown that many programming tasks may
826be significantly simplified by using repeated subexpressions which
827may match zero-length substrings, with a simple example being:
828
829 @chars = split //, $string; # // is not magic in split
830 ($whitewashed = $string) =~ s/()/ /g; # parens avoid magic s// /
831
832Thus Perl allows the C</()/> construct, which I<forcefully breaks
833the infinite loop>. The rules for this are different for lower-level
834loops given by the greedy modifiers C<*+{}>, and for higher-level
835ones like the C</g> modifier or split() operator.
836
837The lower-level loops are I<interrupted> when it is detected that a
838repeated expression did match a zero-length substring, thus
839
840 m{ (?: NON_ZERO_LENGTH | ZERO_LENGTH )* }x;
841
842is made equivalent to
843
844 m{ (?: NON_ZERO_LENGTH )*
845 |
846 (?: ZERO_LENGTH )?
847 }x;
848
849The higher level-loops preserve an additional state between iterations:
850whether the last match was zero-length. To break the loop, the following
851match after a zero-length match is prohibited to have a length of zero.
852This prohibition interacts with backtracking (see L<"Backtracking">),
853and so the I<second best> match is chosen if the I<best> match is of
854zero length.
855
856Say,
857
858 $_ = 'bar';
859 s/\w??/<$&>/g;
860
861results in C<"<><b><><a><><r><>">. At each position of the string the best
862match given by non-greedy C<??> is the zero-length match, and the I<second
863best> match is what is matched by C<\w>. Thus zero-length matches
864alternate with one-character-long matches.
865
866Similarly, for repeated C<m/()/g> the second-best match is the match at the
867position one notch further in the string.
868
869The additional state of being I<matched with zero-length> is associated to
870the matched string, and is reset by each assignment to pos().
871
872=head2 Creating custom RE engines
873
874Overloaded constants (see L<overload>) provide a simple way to extend
875the functionality of the RE engine.
876
877Suppose that we want to enable a new RE escape-sequence C<\Y|> which
878matches at boundary between white-space characters and non-whitespace
879characters. Note that C<(?=\S)(?<!\S)|(?!\S)(?<=\S)> matches exactly
880at these positions, so we want to have each C<\Y|> in the place of the
881more complicated version. We can create a module C<customre> to do
882this:
883
884 package customre;
885 use overload;
886
887 sub import {
888 shift;
889 die "No argument to customre::import allowed" if @_;
890 overload::constant 'qr' => \&convert;
891 }
892
893 sub invalid { die "/$_[0]/: invalid escape '\\$_[1]'"}
894
895 my %rules = ( '\\' => '\\',
896 'Y|' => qr/(?=\S)(?<!\S)|(?!\S)(?<=\S)/ );
897 sub convert {
898 my $re = shift;
899 $re =~ s{
900 \\ ( \\ | Y . )
901 }
902 { $rules{$1} or invalid($re,$1) }sgex;
903 return $re;
904 }
905
906Now C<use customre> enables the new escape in constant regular
907expressions, i.e., those without any runtime variable interpolations.
908As documented in L<overload>, this conversion will work only over
909literal parts of regular expressions. For C<\Y|$re\Y|> the variable
910part of this regular expression needs to be converted explicitly
911(but only if the special meaning of C<\Y|> should be enabled inside $re):
912
913 use customre;
914 $re = <>;
915 chomp $re;
916 $re = customre::convert $re;
917 /\Y|$re\Y|/;
918
9fa51da4
CS
919=head2 SEE ALSO
920
9b599b2a
GS
921L<perlop/"Regexp Quote-Like Operators">.
922
1e66bd83
PP
923L<perlop/"Gory details of parsing quoted constructs">.
924
9b599b2a
GS
925L<perlfunc/pos>.
926
927L<perllocale>.
928
5a964f20 929I<Mastering Regular Expressions> (see L<perlbook>) by Jeffrey Friedl.