3 perlre - Perl regular expressions
7 This page describes the syntax of regular expressions in Perl. For a
8 description of how to I<use> regular expressions in matching
9 operations, plus various examples of the same, see C<m//> and C<s///> in
12 The matching operations can have various modifiers. The modifiers
13 that relate to the interpretation of the regular expression inside
14 are listed below. For the modifiers that alter the behaviour of the
15 operation, see L<perlop/"m//"> and L<perlop/"s//">.
21 Do case-insensitive pattern matching.
23 If C<use locale> is in effect, the case map is taken from the current
24 locale. See L<perllocale>.
28 Treat string as multiple lines. That is, change "^" and "$" from matching
29 at only the very start or end of the string to the start or end of any
30 line anywhere within the string,
34 Treat string as single line. That is, change "." to match any character
35 whatsoever, even a newline, which it normally would not match.
37 The C</s> and C</m> modifiers both override the C<$*> setting. That is, no matter
38 what C<$*> contains, C</s> without C</m> will force "^" to match only at the
39 beginning of the string and "$" to match only at the end (or just before a
40 newline at the end) of the string. Together, as /ms, they let the "." match
41 any character whatsoever, while yet allowing "^" and "$" to match,
42 respectively, just after and just before newlines within the string.
46 Extend your pattern's legibility by permitting whitespace and comments.
50 These are usually written as "the C</x> modifier", even though the delimiter
51 in question might not actually be a slash. In fact, any of these
52 modifiers may also be embedded within the regular expression itself using
53 the new C<(?...)> construct. See below.
55 The C</x> modifier itself needs a little more explanation. It tells
56 the regular expression parser to ignore whitespace that is neither
57 backslashed nor within a character class. You can use this to break up
58 your regular expression into (slightly) more readable parts. The C<#>
59 character is also treated as a metacharacter introducing a comment,
60 just as in ordinary Perl code. This also means that if you want real
61 whitespace or C<#> characters in the pattern (outside of a character
62 class, where they are unaffected by C</x>), that you'll either have to
63 escape them or encode them using octal or hex escapes. Taken together,
64 these features go a long way towards making Perl's regular expressions
65 more readable. Note that you have to be careful not to include the
66 pattern delimiter in the comment--perl has no way of knowing you did
67 not intend to close the pattern early. See the C-comment deletion code
70 =head2 Regular Expressions
72 The patterns used in pattern matching are regular expressions such as
73 those supplied in the Version 8 regex routines. (In fact, the
74 routines are derived (distantly) from Henry Spencer's freely
75 redistributable reimplementation of the V8 routines.)
76 See L<Version 8 Regular Expressions> for details.
78 In particular the following metacharacters have their standard I<egrep>-ish
81 \ Quote the next metacharacter
82 ^ Match the beginning of the line
83 . Match any character (except newline)
84 $ Match the end of the line (or before newline at the end)
89 By default, the "^" character is guaranteed to match at only the
90 beginning of the string, the "$" character at only the end (or before the
91 newline at the end) and Perl does certain optimizations with the
92 assumption that the string contains only one line. Embedded newlines
93 will not be matched by "^" or "$". You may, however, wish to treat a
94 string as a multi-line buffer, such that the "^" will match after any
95 newline within the string, and "$" will match before any newline. At the
96 cost of a little more overhead, you can do this by using the /m modifier
97 on the pattern match operator. (Older programs did this by setting C<$*>,
98 but this practice is now deprecated.)
100 To facilitate multi-line substitutions, the "." character never matches a
101 newline unless you use the C</s> modifier, which in effect tells Perl to pretend
102 the string is a single line--even if it isn't. The C</s> modifier also
103 overrides the setting of C<$*>, in case you have some (badly behaved) older
104 code that sets it in another module.
106 The following standard quantifiers are recognized:
108 * Match 0 or more times
109 + Match 1 or more 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
115 (If a curly bracket occurs in any other context, it is treated
116 as a regular character.) The "*" modifier is equivalent to C<{0,}>, the "+"
117 modifier to C<{1,}>, and the "?" modifier to C<{0,1}>. n and m are limited
118 to integral values less than 65536.
120 By default, a quantified subpattern is "greedy", that is, it will match as
121 many times as possible (given a particular starting location) while still
122 allowing the rest of the pattern to match. If you want it to match the
123 minimum number of times possible, follow the quantifier with a "?". Note
124 that the meanings don't change, just the "greediness":
126 *? Match 0 or more times
127 +? Match 1 or more times
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
133 Because patterns are processed as double quoted strings, the following
140 \a alarm (bell) (BEL)
141 \e escape (think troff) (ESC)
142 \033 octal char (think of a PDP-11)
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)
150 \Q quote (disable) pattern metacharacters till \E
152 If C<use locale> is in effect, the case map used by C<\l>, C<\L>, C<\u>
153 and C<\U> is taken from the current locale. See L<perllocale>.
155 You cannot include a literal C<$> or C<@> within a C<\Q> sequence.
156 An unescaped C<$> or C<@> interpolates the corresponding variable,
157 while escaping will cause the literal string C<\$> to be matched.
158 You'll need to write something like C<m/\Quser\E\@\Qhost/>.
160 In addition, Perl defines the following:
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
169 A C<\w> matches a single alphanumeric character, not a whole
170 word. To match a word you'd need to say C<\w+>. If C<use locale> is in
171 effect, the list of alphabetic characters generated by C<\w> is taken
172 from the current locale. See L<perllocale>. You may use C<\w>, C<\W>,
173 C<\s>, C<\S>, C<\d>, and C<\D> within character classes (though not as
174 either end of a range).
176 Perl defines the following zero-width assertions:
178 \b Match a word boundary
179 \B Match a non-(word boundary)
180 \A Match at only beginning of string
181 \Z Match at only end of string (or before newline at the end)
182 \G Match only where previous m//g left off (works only with /g)
184 A word boundary (C<\b>) is defined as a spot between two characters that
185 has a C<\w> on one side of it and a C<\W> on the other side of it (in
186 either order), counting the imaginary characters off the beginning and
187 end of the string as matching a C<\W>. (Within character classes C<\b>
188 represents backspace rather than a word boundary.) The C<\A> and C<\Z> are
189 just like "^" and "$", except that they won't match multiple times when the
190 C</m> modifier is used, while "^" and "$" will match at every internal line
191 boundary. To match the actual end of the string, not ignoring newline,
192 you can use C<\Z(?!\n)>. The C<\G> assertion can be used to chain global
193 matches (using C<m//g>), as described in
194 L<perlop/"Regexp Quote-Like Operators">.
196 It is also useful when writing C<lex>-like scanners, when you have several
197 patterns that you want to match against consequent substrings of your
198 string, see the previous reference.
199 The actual location where C<\G> will match can also be influenced
200 by using C<pos()> as an lvalue. See L<perlfunc/pos>.
202 When the bracketing construct C<( ... )> is used, \E<lt>digitE<gt> matches the
203 digit'th substring. Outside of the pattern, always use "$" instead of "\"
204 in front of the digit. (While the \E<lt>digitE<gt> notation can on rare occasion work
205 outside the current pattern, this should not be relied upon. See the
206 WARNING below.) The scope of $E<lt>digitE<gt> (and C<$`>, C<$&>, and C<$'>)
207 extends to the end of the enclosing BLOCK or eval string, or to the next
208 successful pattern match, whichever comes first. If you want to use
209 parentheses to delimit a subpattern (e.g., a set of alternatives) without
210 saving it as a subpattern, follow the ( with a ?:.
212 You may have as many parentheses as you wish. If you have more
213 than 9 substrings, the variables $10, $11, ... refer to the
214 corresponding substring. Within the pattern, \10, \11, etc. refer back
215 to substrings if there have been at least that many left parentheses before
216 the backreference. Otherwise (for backward compatibility) \10 is the
217 same as \010, a backspace, and \11 the same as \011, a tab. And so
218 on. (\1 through \9 are always backreferences.)
220 C<$+> returns whatever the last bracket match matched. C<$&> returns the
221 entire matched string. (C<$0> used to return the same thing, but not any
222 more.) C<$`> returns everything before the matched string. C<$'> returns
223 everything after the matched string. Examples:
225 s/^([^ ]*) *([^ ]*)/$2 $1/; # swap first two words
227 if (/Time: (..):(..):(..)/) {
233 Once perl sees that you need one of C<$&>, C<$`> or C<$'> anywhere in
234 the program, it has to provide them on each and every pattern match.
235 This can slow your program down. The same mechanism that handles
236 these provides for the use of $1, $2, etc., so you pay the same price
237 for each pattern that contains capturing parentheses. But if you never
238 use $&, etc., in your script, then patterns I<without> capturing
239 parentheses won't be penalized. So avoid $&, $', and $` if you can,
240 but if you can't (and some algorithms really appreciate them), once
241 you've used them once, use them at will, because you've already paid
242 the price. As of 5.005, $& is not so costly as the other two.
244 Backslashed metacharacters in Perl are
245 alphanumeric, such as C<\b>, C<\w>, C<\n>. Unlike some other regular
246 expression languages, there are no backslashed symbols that aren't
247 alphanumeric. So anything that looks like \\, \(, \), \E<lt>, \E<gt>,
248 \{, or \} is always interpreted as a literal character, not a
249 metacharacter. This was once used in a common idiom to disable or
250 quote the special meanings of regular expression metacharacters in a
251 string that you want to use for a pattern. Simply quote all
252 non-alphanumeric characters:
254 $pattern =~ s/(\W)/\\$1/g;
256 Now it is much more common to see either the quotemeta() function or
257 the C<\Q> escape sequence used to disable all metacharacters' special
260 /$unquoted\Q$quoted\E$unquoted/
262 Perl defines a consistent extension syntax for regular expressions.
263 The syntax is a pair of parentheses with a question mark as the first
264 thing within the parentheses (this was a syntax error in older
265 versions of Perl). The character after the question mark gives the
266 function of the extension. Several extensions are already supported:
272 A comment. The text is ignored. If the C</x> switch is used to enable
273 whitespace formatting, a simple C<#> will suffice.
277 This is for clustering, not capturing; it groups subexpressions like
278 "()", but doesn't make backreferences as "()" does. So
280 @fields = split(/\b(?:a|b|c)\b/)
284 @fields = split(/\b(a|b|c)\b/)
286 but doesn't spit out extra fields.
290 A zero-width positive lookahead assertion. For example, C</\w+(?=\t)/>
291 matches a word followed by a tab, without including the tab in C<$&>.
295 A zero-width negative lookahead assertion. For example C</foo(?!bar)/>
296 matches any occurrence of "foo" that isn't followed by "bar". Note
297 however that lookahead and lookbehind are NOT the same thing. You cannot
298 use this for lookbehind.
300 If you are looking for a "bar" that isn't preceded by a "foo", C</(?!foo)bar/>
301 will not do what you want. That's because the C<(?!foo)> is just saying that
302 the next thing cannot be "foo"--and it's not, it's a "bar", so "foobar" will
303 match. You would have to do something like C</(?!foo)...bar/> for that. We
304 say "like" because there's the case of your "bar" not having three characters
305 before it. You could cover that this way: C</(?:(?!foo)...|^.{0,2})bar/>.
306 Sometimes it's still easier just to say:
308 if (/bar/ && $` !~ /foo$/)
310 For lookbehind see below.
312 =item C<(?E<lt>=pattern)>
314 A zero-width positive lookbehind assertion. For example, C</(?E<lt>=\t)\w+/>
315 matches a word following a tab, without including the tab in C<$&>.
316 Works only for fixed-width lookbehind.
318 =item C<(?<!pattern)>
320 A zero-width negative lookbehind assertion. For example C</(?<!bar)foo/>
321 matches any occurrence of "foo" that isn't following "bar".
322 Works only for fixed-width lookbehind.
326 Experimental "evaluate any Perl code" zero-width assertion. Always
327 succeeds. C<code> is not interpolated. Currently the rules to
328 determine where the C<code> ends are somewhat convoluted.
330 B<WARNING>: This is a grave security risk for arbitrarily interpolated
331 patterns. It introduces security holes in previously safe programs.
332 A fix to Perl, and to this documentation, will be forthcoming prior
333 to the actual 5.005 release.
335 =item C<(?E<gt>pattern)>
337 An "independent" subexpression. Matches the substring that a
338 I<standalone> C<pattern> would match if anchored at the given position,
339 B<and only this substring>.
341 Say, C<^(?E<gt>a*)ab> will never match, since C<(?E<gt>a*)> (anchored
342 at the beginning of string, as above) will match I<all> characters
343 C<a> at the beginning of string, leaving no C<a> for C<ab> to match.
344 In contrast, C<a*ab> will match the same as C<a+b>, since the match of
345 the subgroup C<a*> is influenced by the following group C<ab> (see
346 L<"Backtracking">). In particular, C<a*> inside C<a*ab> will match
347 less characters that a standalone C<a*>, since this makes the tail match.
349 An effect similar to C<(?E<gt>pattern)> may be achieved by
353 since the lookahead is in I<"logical"> context, thus matches the same
354 substring as a standalone C<a+>. The following C<\1> eats the matched
355 string, thus making a zero-length assertion into an analogue of
356 C<(?>...)>. (The difference between these two constructs is that the
357 second one uses a catching group, thus shifting ordinals of
358 backreferences in the rest of a regular expression.)
360 This construct is useful for optimizations of "eternal"
361 matches, because it will not backtrack (see L<"Backtracking">).
371 That will efficiently match a nonempty group with matching
372 two-or-less-level-deep parentheses. However, if there is no such group,
373 it will take virtually forever on a long string. That's because there are
374 so many different ways to split a long string into several substrings.
375 This is essentially what C<(.+)+> is doing, and this is a subpattern
376 of the above pattern. Consider that C<((()aaaaaaaaaaaaaaaaaa> on the
377 pattern above detects no-match in several seconds, but that each extra
378 letter doubles this time. This exponential performance will make it
379 appear that your program has hung.
381 However, a tiny modification of this pattern
391 which uses C<(?E<gt>...)> matches exactly when the one above does (verifying
392 this yourself would be a productive exercise), but finishes in a fourth
393 the time when used on a similar string with 1000000 C<a>s. Be aware,
394 however, that this pattern currently triggers a warning message under
395 B<-w> saying it C<"matches the null string many times">):
397 On simple groups, such as the pattern C<(?> [^()]+ )>, a comparable
398 effect may be achieved by negative lookahead, as in C<[^()]+ (?! [^()] )>.
399 This was only 4 times slower on a string with 1000000 C<a>s.
401 =item C<(?(condition)yes-pattern|no-pattern)>
403 =item C<(?(condition)yes-pattern)>
405 Conditional expression. C<(condition)> should be either an integer in
406 parentheses (which is valid if the corresponding pair of parentheses
407 matched), or lookahead/lookbehind/evaluate zero-width assertion.
416 matches a chunk of non-parentheses, possibly included in parentheses
421 One or more embedded pattern-match modifiers. This is particularly
422 useful for patterns that are specified in a table somewhere, some of
423 which want to be case sensitive, and some of which don't. The case
424 insensitive ones need to include merely C<(?i)> at the front of the
425 pattern. For example:
428 if ( /$pattern/i ) { }
432 $pattern = "(?i)foobar";
433 if ( /$pattern/ ) { }
435 These modifiers are localized inside an enclosing group (if any). Say,
439 (assuming C<x> modifier, and no C<i> modifier outside of this group)
440 will match a repeated (I<including the case>!) word C<blah> in any
445 A question mark was chosen for this and for the new minimal-matching
446 construct because 1) question mark is pretty rare in older regular
447 expressions, and 2) whenever you see one, you should stop and "question"
448 exactly what is going on. That's psychology...
452 A fundamental feature of regular expression matching involves the
453 notion called I<backtracking>, which is currently used (when needed)
454 by all regular expression quantifiers, namely C<*>, C<*?>, C<+>,
455 C<+?>, C<{n,m}>, and C<{n,m}?>.
457 For a regular expression to match, the I<entire> regular expression must
458 match, not just part of it. So if the beginning of a pattern containing a
459 quantifier succeeds in a way that causes later parts in the pattern to
460 fail, the matching engine backs up and recalculates the beginning
461 part--that's why it's called backtracking.
463 Here is an example of backtracking: Let's say you want to find the
464 word following "foo" in the string "Food is on the foo table.":
466 $_ = "Food is on the foo table.";
467 if ( /\b(foo)\s+(\w+)/i ) {
468 print "$2 follows $1.\n";
471 When the match runs, the first part of the regular expression (C<\b(foo)>)
472 finds a possible match right at the beginning of the string, and loads up
473 $1 with "Foo". However, as soon as the matching engine sees that there's
474 no whitespace following the "Foo" that it had saved in $1, it realizes its
475 mistake and starts over again one character after where it had the
476 tentative match. This time it goes all the way until the next occurrence
477 of "foo". The complete regular expression matches this time, and you get
478 the expected output of "table follows foo."
480 Sometimes minimal matching can help a lot. Imagine you'd like to match
481 everything between "foo" and "bar". Initially, you write something
484 $_ = "The food is under the bar in the barn.";
485 if ( /foo(.*)bar/ ) {
489 Which perhaps unexpectedly yields:
491 got <d is under the bar in the >
493 That's because C<.*> was greedy, so you get everything between the
494 I<first> "foo" and the I<last> "bar". In this case, it's more effective
495 to use minimal matching to make sure you get the text between a "foo"
496 and the first "bar" thereafter.
498 if ( /foo(.*?)bar/ ) { print "got <$1>\n" }
499 got <d is under the >
501 Here's another example: let's say you'd like to match a number at the end
502 of a string, and you also want to keep the preceding part the match.
505 $_ = "I have 2 numbers: 53147";
506 if ( /(.*)(\d*)/ ) { # Wrong!
507 print "Beginning is <$1>, number is <$2>.\n";
510 That won't work at all, because C<.*> was greedy and gobbled up the
511 whole string. As C<\d*> can match on an empty string the complete
512 regular expression matched successfully.
514 Beginning is <I have 2 numbers: 53147>, number is <>.
516 Here are some variants, most of which don't work:
518 $_ = "I have 2 numbers: 53147";
531 printf "%-12s ", $pat;
541 (.*)(\d*) <I have 2 numbers: 53147> <>
542 (.*)(\d+) <I have 2 numbers: 5314> <7>
544 (.*?)(\d+) <I have > <2>
545 (.*)(\d+)$ <I have 2 numbers: 5314> <7>
546 (.*?)(\d+)$ <I have 2 numbers: > <53147>
547 (.*)\b(\d+)$ <I have 2 numbers: > <53147>
548 (.*\D)(\d+)$ <I have 2 numbers: > <53147>
550 As you see, this can be a bit tricky. It's important to realize that a
551 regular expression is merely a set of assertions that gives a definition
552 of success. There may be 0, 1, or several different ways that the
553 definition might succeed against a particular string. And if there are
554 multiple ways it might succeed, you need to understand backtracking to
555 know which variety of success you will achieve.
557 When using lookahead assertions and negations, this can all get even
558 tricker. Imagine you'd like to find a sequence of non-digits not
559 followed by "123". You might try to write that as
562 if ( /^\D*(?!123)/ ) { # Wrong!
563 print "Yup, no 123 in $_\n";
566 But that isn't going to match; at least, not the way you're hoping. It
567 claims that there is no 123 in the string. Here's a clearer picture of
568 why it that pattern matches, contrary to popular expectations:
573 print "1: got $1\n" if $x =~ /^(ABC)(?!123)/ ;
574 print "2: got $1\n" if $y =~ /^(ABC)(?!123)/ ;
576 print "3: got $1\n" if $x =~ /^(\D*)(?!123)/ ;
577 print "4: got $1\n" if $y =~ /^(\D*)(?!123)/ ;
585 You might have expected test 3 to fail because it seems to a more
586 general purpose version of test 1. The important difference between
587 them is that test 3 contains a quantifier (C<\D*>) and so can use
588 backtracking, whereas test 1 will not. What's happening is
589 that you've asked "Is it true that at the start of $x, following 0 or more
590 non-digits, you have something that's not 123?" If the pattern matcher had
591 let C<\D*> expand to "ABC", this would have caused the whole pattern to
593 The search engine will initially match C<\D*> with "ABC". Then it will
594 try to match C<(?!123> with "123", which of course fails. But because
595 a quantifier (C<\D*>) has been used in the regular expression, the
596 search engine can backtrack and retry the match differently
597 in the hope of matching the complete regular expression.
599 The pattern really, I<really> wants to succeed, so it uses the
600 standard pattern back-off-and-retry and lets C<\D*> expand to just "AB" this
601 time. Now there's indeed something following "AB" that is not
602 "123". It's in fact "C123", which suffices.
604 We can deal with this by using both an assertion and a negation. We'll
605 say that the first part in $1 must be followed by a digit, and in fact, it
606 must also be followed by something that's not "123". Remember that the
607 lookaheads are zero-width expressions--they only look, but don't consume
608 any of the string in their match. So rewriting this way produces what
609 you'd expect; that is, case 5 will fail, but case 6 succeeds:
611 print "5: got $1\n" if $x =~ /^(\D*)(?=\d)(?!123)/ ;
612 print "6: got $1\n" if $y =~ /^(\D*)(?=\d)(?!123)/ ;
616 In other words, the two zero-width assertions next to each other work as though
617 they're ANDed together, just as you'd use any builtin assertions: C</^$/>
618 matches only if you're at the beginning of the line AND the end of the
619 line simultaneously. The deeper underlying truth is that juxtaposition in
620 regular expressions always means AND, except when you write an explicit OR
621 using the vertical bar. C</ab/> means match "a" AND (then) match "b",
622 although the attempted matches are made at different positions because "a"
623 is not a zero-width assertion, but a one-width assertion.
625 One warning: particularly complicated regular expressions can take
626 exponential time to solve due to the immense number of possible ways they
627 can use backtracking to try match. For example this will take a very long
630 /((a{0,5}){0,5}){0,5}/
632 And if you used C<*>'s instead of limiting it to 0 through 5 matches, then
633 it would take literally forever--or until you ran out of stack space.
635 A powerful tool for optimizing such beasts is "independent" groups,
636 which do not backtrace (see L<C<(?E<gt>pattern)>>). Note also that
637 zero-length lookahead/lookbehind assertions will not backtrace to make
638 the tail match, since they are in "logical" context: only the fact
639 whether they match or not is considered relevant. For an example
640 where side-effects of a lookahead I<might> have influenced the
641 following match, see L<C<(?E<gt>pattern)>>.
643 =head2 Version 8 Regular Expressions
645 In case you're not familiar with the "regular" Version 8 regex
646 routines, here are the pattern-matching rules not described above.
648 Any single character matches itself, unless it is a I<metacharacter>
649 with a special meaning described here or above. You can cause
650 characters that normally function as metacharacters to be interpreted
651 literally by prefixing them with a "\" (e.g., "\." matches a ".", not any
652 character; "\\" matches a "\"). A series of characters matches that
653 series of characters in the target string, so the pattern C<blurfl>
654 would match "blurfl" in the target string.
656 You can specify a character class, by enclosing a list of characters
657 in C<[]>, which will match any one character from the list. If the
658 first character after the "[" is "^", the class matches any character not
659 in the list. Within a list, the "-" character is used to specify a
660 range, so that C<a-z> represents all characters between "a" and "z",
661 inclusive. If you want "-" itself to be a member of a class, put it
662 at the start or end of the list, or escape it with a backslash. (The
663 following all specify the same class of three characters: C<[-az]>,
664 C<[az-]>, and C<[a\-z]>. All are different from C<[a-z]>, which
665 specifies a class containing twenty-six characters.)
667 Characters may be specified using a metacharacter syntax much like that
668 used in C: "\n" matches a newline, "\t" a tab, "\r" a carriage return,
669 "\f" a form feed, etc. More generally, \I<nnn>, where I<nnn> is a string
670 of octal digits, matches the character whose ASCII value is I<nnn>.
671 Similarly, \xI<nn>, where I<nn> are hexadecimal digits, matches the
672 character whose ASCII value is I<nn>. The expression \cI<x> matches the
673 ASCII character control-I<x>. Finally, the "." metacharacter matches any
674 character except "\n" (unless you use C</s>).
676 You can specify a series of alternatives for a pattern using "|" to
677 separate them, so that C<fee|fie|foe> will match any of "fee", "fie",
678 or "foe" in the target string (as would C<f(e|i|o)e>). The
679 first alternative includes everything from the last pattern delimiter
680 ("(", "[", or the beginning of the pattern) up to the first "|", and
681 the last alternative contains everything from the last "|" to the next
682 pattern delimiter. For this reason, it's common practice to include
683 alternatives in parentheses, to minimize confusion about where they
686 Alternatives are tried from left to right, so the first
687 alternative found for which the entire expression matches, is the one that
688 is chosen. This means that alternatives are not necessarily greedy. For
689 example: when mathing C<foo|foot> against "barefoot", only the "foo"
690 part will match, as that is the first alternative tried, and it successfully
691 matches the target string. (This might not seem important, but it is
692 important when you are capturing matched text using parentheses.)
694 Also remember that "|" is interpreted as a literal within square brackets,
695 so if you write C<[fee|fie|foe]> you're really only matching C<[feio|]>.
697 Within a pattern, you may designate subpatterns for later reference by
698 enclosing them in parentheses, and you may refer back to the I<n>th
699 subpattern later in the pattern using the metacharacter \I<n>.
700 Subpatterns are numbered based on the left to right order of their
701 opening parenthesis. A backreference matches whatever
702 actually matched the subpattern in the string being examined, not the
703 rules for that subpattern. Therefore, C<(0|0x)\d*\s\1\d*> will
704 match "0x1234 0x4321", but not "0x1234 01234", because subpattern 1
705 actually matched "0x", even though the rule C<0|0x> could
706 potentially match the leading 0 in the second number.
708 =head2 WARNING on \1 vs $1
710 Some people get too used to writing things like:
712 $pattern =~ s/(\W)/\\\1/g;
714 This is grandfathered for the RHS of a substitute to avoid shocking the
715 B<sed> addicts, but it's a dirty habit to get into. That's because in
716 PerlThink, the righthand side of a C<s///> is a double-quoted string. C<\1> in
717 the usual double-quoted string means a control-A. The customary Unix
718 meaning of C<\1> is kludged in for C<s///>. However, if you get into the habit
719 of doing that, you get yourself into trouble if you then add an C</e>
722 s/(\d+)/ \1 + 1 /eg; # causes warning under -w
728 You can't disambiguate that by saying C<\{1}000>, whereas you can fix it with
729 C<${1}000>. Basically, the operation of interpolation should not be confused
730 with the operation of matching a backreference. Certainly they mean two
731 different things on the I<left> side of the C<s///>.
735 L<perlop/"Regexp Quote-Like Operators">.
741 I<Mastering Regular Expressions> (see L<perlbook>) by Jeffrey Friedl.