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