2 X<regular expression> X<regex> X<regexp>
4 perlre - Perl regular expressions
8 This page describes the syntax of regular expressions in Perl.
10 If you haven't used regular expressions before, a quick-start
11 introduction is available in L<perlrequick>, and a longer tutorial
12 introduction is available in L<perlretut>.
14 For reference on how regular expressions are used in matching
15 operations, plus various examples of the same, see discussions of
16 C<m//>, C<s///>, C<qr//> and C<??> in L<perlop/"Regexp Quote-Like
22 Matching operations can have various modifiers. Modifiers
23 that relate to the interpretation of the regular expression inside
24 are listed below. Modifiers that alter the way a regular expression
25 is used by Perl are detailed in L<perlop/"Regexp Quote-Like Operators"> and
26 L<perlop/"Gory details of parsing quoted constructs">.
31 X</m> X<regex, multiline> X<regexp, multiline> X<regular expression, multiline>
33 Treat string as multiple lines. That is, change "^" and "$" from matching
34 the start of the string's first line and the end of its last line to
35 matching the start and end of each line within the string.
38 X</s> X<regex, single-line> X<regexp, single-line>
39 X<regular expression, single-line>
41 Treat string as single line. That is, change "." to match any character
42 whatsoever, even a newline, which normally it would not match.
44 Used together, as C</ms>, they let the "." match any character whatsoever,
45 while still allowing "^" and "$" to match, respectively, just after
46 and just before newlines within the string.
49 X</i> X<regex, case-insensitive> X<regexp, case-insensitive>
50 X<regular expression, case-insensitive>
52 Do case-insensitive pattern matching.
54 If locale matching rules are in effect, the case map is taken from the
56 locale for code points less than 255, and from Unicode rules for larger
57 code points. However, matches that would cross the Unicode
58 rules/non-Unicode rules boundary (ords 255/256) will not succeed. See
61 There are a number of Unicode characters that match multiple characters
62 under C</i>. For example, C<LATIN SMALL LIGATURE FI>
63 should match the sequence C<fi>. Perl is not
64 currently able to do this when the multiple characters are in the pattern and
65 are split between groupings, or when one or more are quantified. Thus
67 "\N{LATIN SMALL LIGATURE FI}" =~ /fi/i; # Matches
68 "\N{LATIN SMALL LIGATURE FI}" =~ /[fi][fi]/i; # Doesn't match!
69 "\N{LATIN SMALL LIGATURE FI}" =~ /fi*/i; # Doesn't match!
71 # The below doesn't match, and it isn't clear what $1 and $2 would
73 "\N{LATIN SMALL LIGATURE FI}" =~ /(f)(i)/i; # Doesn't match!
75 Perl doesn't match multiple characters in a bracketed
76 character class unless the character that maps to them is explicitly
77 mentioned, and it doesn't match them at all if the character class is
78 inverted, which otherwise could be highly confusing. See
79 L<perlrecharclass/Bracketed Character Classes>, and
80 L<perlrecharclass/Negation>.
85 Extend your pattern's legibility by permitting whitespace and comments.
89 X</p> X<regex, preserve> X<regexp, preserve>
91 Preserve the string matched such that ${^PREMATCH}, ${^MATCH}, and
92 ${^POSTMATCH} are available for use after matching.
94 In Perl 5.20 and higher this is ignored. Due to a new copy-on-write
95 mechanism, ${^PREMATCH}, ${^MATCH}, and ${^POSTMATCH} will be available
96 after the match regardless of the modifier.
99 X</a> X</d> X</l> X</u>
101 These modifiers, all new in 5.14, affect which character-set rules
102 (Unicode, etc.) are used, as described below in
103 L</Character set modifiers>.
106 X</n> X<regex, non-capture> X<regexp, non-capture>
107 X<regular expression, non-capture>
109 Prevent the grouping metacharacters C<()> from capturing. This modifier,
110 new in 5.22, will stop C<$1>, C<$2>, etc... from being filled in.
112 "hello" =~ /(hi|hello)/; # $1 is "hello"
113 "hello" =~ /(hi|hello)/n; # $1 is undef
115 This is equivalent to putting ?: at the beginning of every capturing group:
117 "hello" =~ /(?:hi|hello)/; # $1 is undef
119 C</n> can be negated on a per-group basis. Alternatively, named captures
122 "hello" =~ /(?-n:(hi|hello))/n; # $1 is "hello"
123 "hello" =~ /(?<greet>hi|hello)/n; # $1 is "hello", $+{greet} is "hello"
125 =item Other Modifiers
127 There are a number of flags that can be found at the end of regular
128 expression constructs that are I<not> generic regular expression flags, but
129 apply to the operation being performed, like matching or substitution (C<m//>
130 or C<s///> respectively).
132 Flags described further in
133 L<perlretut/"Using regular expressions in Perl"> are:
135 c - keep the current position during repeated matching
136 g - globally match the pattern repeatedly in the string
138 Substitution-specific modifiers described in
140 L<perlop/"s/PATTERN/REPLACEMENT/msixpodualngcer"> are:
142 e - evaluate the right-hand side as an expression
143 ee - evaluate the right side as a string then eval the result
144 o - pretend to optimize your code, but actually introduce bugs
145 r - perform non-destructive substitution and return the new value
149 Regular expression modifiers are usually written in documentation
150 as e.g., "the C</x> modifier", even though the delimiter
151 in question might not really be a slash. The modifiers C</imsxadlup>
152 may also be embedded within the regular expression itself using
153 the C<(?...)> construct, see L</Extended Patterns> below.
158 the regular expression parser to ignore most whitespace that is neither
159 backslashed nor within a bracketed character class. You can use this to
160 break up your regular expression into (slightly) more readable parts.
161 Also, the C<#> character is treated as a metacharacter introducing a
162 comment that runs up to the pattern's closing delimiter, or to the end
163 of the current line if the pattern extends onto the next line. Hence,
164 this is very much like an ordinary Perl code comment. (You can include
165 the closing delimiter within the comment only if you precede it with a
166 backslash, so be careful!)
168 Use of C</x> means that if you want real
169 whitespace or C<#> characters in the pattern (outside a bracketed character
170 class, which is unaffected by C</x>), then you'll either have to
171 escape them (using backslashes or C<\Q...\E>) or encode them using octal,
172 hex, or C<\N{}> escapes.
173 It is ineffective to try to continue a comment onto the next line by
174 escaping the C<\n> with a backslash or C<\Q>.
176 You can use L</(?#text)> to create a comment that ends earlier than the
177 end of the current line, but C<text> also can't contain the closing
178 delimiter unless escaped with a backslash.
180 Taken together, these features go a long way towards
181 making Perl's regular expressions more readable. Here's an example:
183 # Delete (most) C comments.
185 /\* # Match the opening delimiter.
186 .*? # Match a minimal number of characters.
187 \*/ # Match the closing delimiter.
190 Note that anything inside
191 a C<\Q...\E> stays unaffected by C</x>. And note that C</x> doesn't affect
192 space interpretation within a single multi-character construct. For
193 example in C<\x{...}>, regardless of the C</x> modifier, there can be no
194 spaces. Same for a L<quantifier|/Quantifiers> such as C<{3}> or
195 C<{5,}>. Similarly, C<(?:...)> can't have a space between the C<(>,
196 C<?>, and C<:>. Within any delimiters for such a
197 construct, allowed spaces are not affected by C</x>, and depend on the
198 construct. For example, C<\x{...}> can't have spaces because hexadecimal
199 numbers don't have spaces in them. But, Unicode properties can have spaces, so
200 in C<\p{...}> there can be spaces that follow the Unicode rules, for which see
201 L<perluniprops/Properties accessible through \p{} and \P{}>.
204 The set of characters that are deemed whitespace are those that Unicode
205 calls "Pattern White Space", namely:
207 U+0009 CHARACTER TABULATION
209 U+000B LINE TABULATION
211 U+000D CARRIAGE RETURN
214 U+200E LEFT-TO-RIGHT MARK
215 U+200F RIGHT-TO-LEFT MARK
216 U+2028 LINE SEPARATOR
217 U+2029 PARAGRAPH SEPARATOR
219 =head3 Character set modifiers
221 C</d>, C</u>, C</a>, and C</l>, available starting in 5.14, are called
222 the character set modifiers; they affect the character set rules
223 used for the regular expression.
225 The C</d>, C</u>, and C</l> modifiers are not likely to be of much use
226 to you, and so you need not worry about them very much. They exist for
227 Perl's internal use, so that complex regular expression data structures
228 can be automatically serialized and later exactly reconstituted,
229 including all their nuances. But, since Perl can't keep a secret, and
230 there may be rare instances where they are useful, they are documented
233 The C</a> modifier, on the other hand, may be useful. Its purpose is to
234 allow code that is to work mostly on ASCII data to not have to concern
237 Briefly, C</l> sets the character set to that of whatever B<L>ocale is in
238 effect at the time of the execution of the pattern match.
240 C</u> sets the character set to B<U>nicode.
242 C</a> also sets the character set to Unicode, BUT adds several
243 restrictions for B<A>SCII-safe matching.
245 C</d> is the old, problematic, pre-5.14 B<D>efault character set
246 behavior. Its only use is to force that old behavior.
248 At any given time, exactly one of these modifiers is in effect. Their
249 existence allows Perl to keep the originally compiled behavior of a
250 regular expression, regardless of what rules are in effect when it is
251 actually executed. And if it is interpolated into a larger regex, the
252 original's rules continue to apply to it, and only it.
254 The C</l> and C</u> modifiers are automatically selected for
255 regular expressions compiled within the scope of various pragmas,
256 and we recommend that in general, you use those pragmas instead of
257 specifying these modifiers explicitly. For one thing, the modifiers
258 affect only pattern matching, and do not extend to even any replacement
259 done, whereas using the pragmas give consistent results for all
260 appropriate operations within their scopes. For example,
264 will match "foo" using the locale's rules for case-insensitive matching,
265 but the C</l> does not affect how the C<\U> operates. Most likely you
266 want both of them to use locale rules. To do this, instead compile the
267 regular expression within the scope of C<use locale>. This both
268 implicitly adds the C</l> and applies locale rules to the C<\U>. The
269 lesson is to C<use locale> and not C</l> explicitly.
271 Similarly, it would be better to use C<use feature 'unicode_strings'>
276 to get Unicode rules, as the C<\L> in the former (but not necessarily
277 the latter) would also use Unicode rules.
279 More detail on each of the modifiers follows. Most likely you don't
280 need to know this detail for C</l>, C</u>, and C</d>, and can skip ahead
281 to L<E<sol>a|/E<sol>a (and E<sol>aa)>.
285 means to use the current locale's rules (see L<perllocale>) when pattern
286 matching. For example, C<\w> will match the "word" characters of that
287 locale, and C<"/i"> case-insensitive matching will match according to
288 the locale's case folding rules. The locale used will be the one in
289 effect at the time of execution of the pattern match. This may not be
290 the same as the compilation-time locale, and can differ from one match
291 to another if there is an intervening call of the
292 L<setlocale() function|perllocale/The setlocale function>.
294 The only non-single-byte locale Perl supports is (starting in v5.20)
295 UTF-8. This means that code points above 255 are treated as Unicode no
296 matter what locale is in effect (since UTF-8 implies Unicode).
298 Under Unicode rules, there are a few case-insensitive matches that cross
299 the 255/256 boundary. Except for UTF-8 locales in Perls v5.20 and
300 later, these are disallowed under C</l>. For example, 0xFF (on ASCII
301 platforms) does not caselessly match the character at 0x178, C<LATIN
302 CAPITAL LETTER Y WITH DIAERESIS>, because 0xFF may not be C<LATIN SMALL
303 LETTER Y WITH DIAERESIS> in the current locale, and Perl has no way of
304 knowing if that character even exists in the locale, much less what code
307 In a UTF-8 locale in v5.20 and later, the only visible difference
308 between locale and non-locale in regular expressions should be tainting
311 This modifier may be specified to be the default by C<use locale>, but
312 see L</Which character set modifier is in effect?>.
317 means to use Unicode rules when pattern matching. On ASCII platforms,
318 this means that the code points between 128 and 255 take on their
319 Latin-1 (ISO-8859-1) meanings (which are the same as Unicode's).
320 (Otherwise Perl considers their meanings to be undefined.) Thus,
321 under this modifier, the ASCII platform effectively becomes a Unicode
322 platform; and hence, for example, C<\w> will match any of the more than
323 100_000 word characters in Unicode.
325 Unlike most locales, which are specific to a language and country pair,
326 Unicode classifies all the characters that are letters I<somewhere> in
328 C<\w>. For example, your locale might not think that C<LATIN SMALL
329 LETTER ETH> is a letter (unless you happen to speak Icelandic), but
330 Unicode does. Similarly, all the characters that are decimal digits
331 somewhere in the world will match C<\d>; this is hundreds, not 10,
332 possible matches. And some of those digits look like some of the 10
333 ASCII digits, but mean a different number, so a human could easily think
334 a number is a different quantity than it really is. For example,
335 C<BENGALI DIGIT FOUR> (U+09EA) looks very much like an
336 C<ASCII DIGIT EIGHT> (U+0038). And, C<\d+>, may match strings of digits
337 that are a mixture from different writing systems, creating a security
338 issue. L<Unicode::UCD/num()> can be used to sort
339 this out. Or the C</a> modifier can be used to force C<\d> to match
340 just the ASCII 0 through 9.
342 Also, under this modifier, case-insensitive matching works on the full
344 characters. The C<KELVIN SIGN>, for example matches the letters "k" and
345 "K"; and C<LATIN SMALL LIGATURE FF> matches the sequence "ff", which,
346 if you're not prepared, might make it look like a hexadecimal constant,
347 presenting another potential security issue. See
348 L<http://unicode.org/reports/tr36> for a detailed discussion of Unicode
351 This modifier may be specified to be the default by C<use feature
352 'unicode_strings>, C<use locale ':not_characters'>, or
353 C<L<use 5.012|perlfunc/use VERSION>> (or higher),
354 but see L</Which character set modifier is in effect?>.
359 This modifier means to use the "Default" native rules of the platform
360 except when there is cause to use Unicode rules instead, as follows:
366 the target string is encoded in UTF-8; or
370 the pattern is encoded in UTF-8; or
374 the pattern explicitly mentions a code point that is above 255 (say by
379 the pattern uses a Unicode name (C<\N{...}>); or
383 the pattern uses a Unicode property (C<\p{...}>); or
387 the pattern uses L</C<(?[ ])>>
391 Another mnemonic for this modifier is "Depends", as the rules actually
392 used depend on various things, and as a result you can get unexpected
393 results. See L<perlunicode/The "Unicode Bug">. The Unicode Bug has
394 become rather infamous, leading to yet another (printable) name for this
397 Unless the pattern or string are encoded in UTF-8, only ASCII characters
398 can match positively.
400 Here are some examples of how that works on an ASCII platform:
402 $str = "\xDF"; # $str is not in UTF-8 format.
403 $str =~ /^\w/; # No match, as $str isn't in UTF-8 format.
404 $str .= "\x{0e0b}"; # Now $str is in UTF-8 format.
405 $str =~ /^\w/; # Match! $str is now in UTF-8 format.
407 $str =~ /^\w/; # Still a match! $str remains in UTF-8 format.
409 This modifier is automatically selected by default when none of the
410 others are, so yet another name for it is "Default".
412 Because of the unexpected behaviors associated with this modifier, you
413 probably should only use it to maintain weird backward compatibilities.
417 This modifier stands for ASCII-restrict (or ASCII-safe). This modifier,
418 unlike the others, may be doubled-up to increase its effect.
420 When it appears singly, it causes the sequences C<\d>, C<\s>, C<\w>, and
421 the Posix character classes to match only in the ASCII range. They thus
422 revert to their pre-5.6, pre-Unicode meanings. Under C</a>, C<\d>
423 always means precisely the digits C<"0"> to C<"9">; C<\s> means the five
424 characters C<[ \f\n\r\t]>, and starting in Perl v5.18, experimentally,
425 the vertical tab; C<\w> means the 63 characters
426 C<[A-Za-z0-9_]>; and likewise, all the Posix classes such as
427 C<[[:print:]]> match only the appropriate ASCII-range characters.
429 This modifier is useful for people who only incidentally use Unicode,
430 and who do not wish to be burdened with its complexities and security
433 With C</a>, one can write C<\d> with confidence that it will only match
434 ASCII characters, and should the need arise to match beyond ASCII, you
435 can instead use C<\p{Digit}> (or C<\p{Word}> for C<\w>). There are
436 similar C<\p{...}> constructs that can match beyond ASCII both white
437 space (see L<perlrecharclass/Whitespace>), and Posix classes (see
438 L<perlrecharclass/POSIX Character Classes>). Thus, this modifier
439 doesn't mean you can't use Unicode, it means that to get Unicode
440 matching you must explicitly use a construct (C<\p{}>, C<\P{}>) that
443 As you would expect, this modifier causes, for example, C<\D> to mean
444 the same thing as C<[^0-9]>; in fact, all non-ASCII characters match
445 C<\D>, C<\S>, and C<\W>. C<\b> still means to match at the boundary
446 between C<\w> and C<\W>, using the C</a> definitions of them (similarly
449 Otherwise, C</a> behaves like the C</u> modifier, in that
450 case-insensitive matching uses Unicode rules; for example, "k" will
451 match the Unicode C<\N{KELVIN SIGN}> under C</i> matching, and code
452 points in the Latin1 range, above ASCII will have Unicode rules when it
453 comes to case-insensitive matching.
455 To forbid ASCII/non-ASCII matches (like "k" with C<\N{KELVIN SIGN}>),
456 specify the "a" twice, for example C</aai> or C</aia>. (The first
457 occurrence of "a" restricts the C<\d>, etc., and the second occurrence
458 adds the C</i> restrictions.) But, note that code points outside the
459 ASCII range will use Unicode rules for C</i> matching, so the modifier
460 doesn't really restrict things to just ASCII; it just forbids the
461 intermixing of ASCII and non-ASCII.
463 To summarize, this modifier provides protection for applications that
464 don't wish to be exposed to all of Unicode. Specifying it twice
465 gives added protection.
467 This modifier may be specified to be the default by C<use re '/a'>
468 or C<use re '/aa'>. If you do so, you may actually have occasion to use
469 the C</u> modifier explicitly if there are a few regular expressions
470 where you do want full Unicode rules (but even here, it's best if
471 everything were under feature C<"unicode_strings">, along with the
472 C<use re '/aa'>). Also see L</Which character set modifier is in
477 =head4 Which character set modifier is in effect?
479 Which of these modifiers is in effect at any given point in a regular
480 expression depends on a fairly complex set of interactions. These have
481 been designed so that in general you don't have to worry about it, but
482 this section gives the gory details. As
483 explained below in L</Extended Patterns> it is possible to explicitly
484 specify modifiers that apply only to portions of a regular expression.
485 The innermost always has priority over any outer ones, and one applying
486 to the whole expression has priority over any of the default settings that are
487 described in the remainder of this section.
489 The C<L<use re 'E<sol>foo'|re/"'/flags' mode">> pragma can be used to set
490 default modifiers (including these) for regular expressions compiled
491 within its scope. This pragma has precedence over the other pragmas
492 listed below that also change the defaults.
494 Otherwise, C<L<use locale|perllocale>> sets the default modifier to C</l>;
495 and C<L<use feature 'unicode_strings|feature>>, or
496 C<L<use 5.012|perlfunc/use VERSION>> (or higher) set the default to
497 C</u> when not in the same scope as either C<L<use locale|perllocale>>
498 or C<L<use bytes|bytes>>.
499 (C<L<use locale ':not_characters'|perllocale/Unicode and UTF-8>> also
500 sets the default to C</u>, overriding any plain C<use locale>.)
501 Unlike the mechanisms mentioned above, these
502 affect operations besides regular expressions pattern matching, and so
503 give more consistent results with other operators, including using
504 C<\U>, C<\l>, etc. in substitution replacements.
506 If none of the above apply, for backwards compatibility reasons, the
507 C</d> modifier is the one in effect by default. As this can lead to
508 unexpected results, it is best to specify which other rule set should be
511 =head4 Character set modifier behavior prior to Perl 5.14
513 Prior to 5.14, there were no explicit modifiers, but C</l> was implied
514 for regexes compiled within the scope of C<use locale>, and C</d> was
515 implied otherwise. However, interpolating a regex into a larger regex
516 would ignore the original compilation in favor of whatever was in effect
517 at the time of the second compilation. There were a number of
518 inconsistencies (bugs) with the C</d> modifier, where Unicode rules
519 would be used when inappropriate, and vice versa. C<\p{}> did not imply
520 Unicode rules, and neither did all occurrences of C<\N{}>, until 5.12.
522 =head2 Regular Expressions
524 =head3 Metacharacters
526 The patterns used in Perl pattern matching evolved from those supplied in
527 the Version 8 regex routines. (The routines are derived
528 (distantly) from Henry Spencer's freely redistributable reimplementation
529 of the V8 routines.) See L<Version 8 Regular Expressions> for
532 In particular the following metacharacters have their standard I<egrep>-ish
535 X<\> X<^> X<.> X<$> X<|> X<(> X<()> X<[> X<[]>
538 \ Quote the next metacharacter
539 ^ Match the beginning of the line
540 . Match any character (except newline)
541 $ Match the end of the string (or before newline at the end
545 [] Bracketed Character class
547 By default, the "^" character is guaranteed to match only the
548 beginning of the string, the "$" character only the end (or before the
549 newline at the end), and Perl does certain optimizations with the
550 assumption that the string contains only one line. Embedded newlines
551 will not be matched by "^" or "$". You may, however, wish to treat a
552 string as a multi-line buffer, such that the "^" will match after any
553 newline within the string (except if the newline is the last character in
554 the string), and "$" will match before any newline. At the
555 cost of a little more overhead, you can do this by using the /m modifier
556 on the pattern match operator. (Older programs did this by setting C<$*>,
557 but this option was removed in perl 5.10.)
560 To simplify multi-line substitutions, the "." character never matches a
561 newline unless you use the C</s> modifier, which in effect tells Perl to pretend
562 the string is a single line--even if it isn't.
567 The following standard quantifiers are recognized:
568 X<metacharacter> X<quantifier> X<*> X<+> X<?> X<{n}> X<{n,}> X<{n,m}>
570 * Match 0 or more times
571 + Match 1 or more times
573 {n} Match exactly n times
574 {n,} Match at least n times
575 {n,m} Match at least n but not more than m times
577 (If a curly bracket occurs in any other context and does not form part of
578 a backslashed sequence like C<\x{...}>, it is treated as a regular
579 character. However, a deprecation warning is raised for all such
580 occurrences, and in Perl v5.26, literal uses of a curly bracket will be
581 required to be escaped, say by preceding them with a backslash (C<"\{">)
582 or enclosing them within square brackets (C<"[{]">). This change will
583 allow for future syntax extensions (like making the lower bound of a
584 quantifier optional), and better error checking of quantifiers.)
586 The "*" quantifier is equivalent to C<{0,}>, the "+"
587 quantifier to C<{1,}>, and the "?" quantifier to C<{0,1}>. n and m are limited
588 to non-negative integral values less than a preset limit defined when perl is built.
589 This is usually 32766 on the most common platforms. The actual limit can
590 be seen in the error message generated by code such as this:
592 $_ **= $_ , / {$_} / for 2 .. 42;
594 By default, a quantified subpattern is "greedy", that is, it will match as
595 many times as possible (given a particular starting location) while still
596 allowing the rest of the pattern to match. If you want it to match the
597 minimum number of times possible, follow the quantifier with a "?". Note
598 that the meanings don't change, just the "greediness":
599 X<metacharacter> X<greedy> X<greediness>
600 X<?> X<*?> X<+?> X<??> X<{n}?> X<{n,}?> X<{n,m}?>
602 *? Match 0 or more times, not greedily
603 +? Match 1 or more times, not greedily
604 ?? Match 0 or 1 time, not greedily
605 {n}? Match exactly n times, not greedily (redundant)
606 {n,}? Match at least n times, not greedily
607 {n,m}? Match at least n but not more than m times, not greedily
609 Normally when a quantified subpattern does not allow the rest of the
610 overall pattern to match, Perl will backtrack. However, this behaviour is
611 sometimes undesirable. Thus Perl provides the "possessive" quantifier form
614 *+ Match 0 or more times and give nothing back
615 ++ Match 1 or more times and give nothing back
616 ?+ Match 0 or 1 time and give nothing back
617 {n}+ Match exactly n times and give nothing back (redundant)
618 {n,}+ Match at least n times and give nothing back
619 {n,m}+ Match at least n but not more than m times and give nothing back
625 will never match, as the C<a++> will gobble up all the C<a>'s in the
626 string and won't leave any for the remaining part of the pattern. This
627 feature can be extremely useful to give perl hints about where it
628 shouldn't backtrack. For instance, the typical "match a double-quoted
629 string" problem can be most efficiently performed when written as:
631 /"(?:[^"\\]++|\\.)*+"/
633 as we know that if the final quote does not match, backtracking will not
634 help. See the independent subexpression
635 L</C<< (?>pattern) >>> for more details;
636 possessive quantifiers are just syntactic sugar for that construct. For
637 instance the above example could also be written as follows:
639 /"(?>(?:(?>[^"\\]+)|\\.)*)"/
641 Note that the possessive quantifier modifier can not be be combined
642 with the non-greedy modifier. This is because it would make no sense.
643 Consider the follow equivalency table:
651 =head3 Escape sequences
653 Because patterns are processed as double-quoted strings, the following
660 \a alarm (bell) (BEL)
661 \e escape (think troff) (ESC)
662 \cK control char (example: VT)
663 \x{}, \x00 character whose ordinal is the given hexadecimal number
664 \N{name} named Unicode character or character sequence
665 \N{U+263D} Unicode character (example: FIRST QUARTER MOON)
666 \o{}, \000 character whose ordinal is the given octal number
667 \l lowercase next char (think vi)
668 \u uppercase next char (think vi)
669 \L lowercase until \E (think vi)
670 \U uppercase until \E (think vi)
671 \Q quote (disable) pattern metacharacters until \E
672 \E end either case modification or quoted section, think vi
674 Details are in L<perlop/Quote and Quote-like Operators>.
676 =head3 Character Classes and other Special Escapes
678 In addition, Perl defines the following:
679 X<\g> X<\k> X<\K> X<backreference>
681 Sequence Note Description
682 [...] [1] Match a character according to the rules of the
683 bracketed character class defined by the "...".
684 Example: [a-z] matches "a" or "b" or "c" ... or "z"
685 [[:...:]] [2] Match a character according to the rules of the POSIX
686 character class "..." within the outer bracketed
687 character class. Example: [[:upper:]] matches any
689 (?[...]) [8] Extended bracketed character class
690 \w [3] Match a "word" character (alphanumeric plus "_", plus
691 other connector punctuation chars plus Unicode
693 \W [3] Match a non-"word" character
694 \s [3] Match a whitespace character
695 \S [3] Match a non-whitespace character
696 \d [3] Match a decimal digit character
697 \D [3] Match a non-digit character
698 \pP [3] Match P, named property. Use \p{Prop} for longer names
700 \X [4] Match Unicode "eXtended grapheme cluster"
701 \C Match a single C-language char (octet) even if that is
702 part of a larger UTF-8 character. Thus it breaks up
703 characters into their UTF-8 bytes, so you may end up
704 with malformed pieces of UTF-8. Unsupported in
705 lookbehind. (Deprecated.)
706 \1 [5] Backreference to a specific capture group or buffer.
707 '1' may actually be any positive integer.
708 \g1 [5] Backreference to a specific or previous group,
709 \g{-1} [5] The number may be negative indicating a relative
710 previous group and may optionally be wrapped in
711 curly brackets for safer parsing.
712 \g{name} [5] Named backreference
713 \k<name> [5] Named backreference
714 \K [6] Keep the stuff left of the \K, don't include it in $&
715 \N [7] Any character but \n. Not affected by /s modifier
716 \v [3] Vertical whitespace
717 \V [3] Not vertical whitespace
718 \h [3] Horizontal whitespace
719 \H [3] Not horizontal whitespace
726 See L<perlrecharclass/Bracketed Character Classes> for details.
730 See L<perlrecharclass/POSIX Character Classes> for details.
734 See L<perlrecharclass/Backslash sequences> for details.
738 See L<perlrebackslash/Misc> for details.
742 See L</Capture groups> below for details.
746 See L</Extended Patterns> below for details.
750 Note that C<\N> has two meanings. When of the form C<\N{NAME}>, it matches the
751 character or character sequence whose name is C<NAME>; and similarly
752 when of the form C<\N{U+I<hex>}>, it matches the character whose Unicode
753 code point is I<hex>. Otherwise it matches any character but C<\n>.
757 See L<perlrecharclass/Extended Bracketed Character Classes> for details.
763 Perl defines the following zero-width assertions:
764 X<zero-width assertion> X<assertion> X<regex, zero-width assertion>
765 X<regexp, zero-width assertion>
766 X<regular expression, zero-width assertion>
767 X<\b> X<\B> X<\A> X<\Z> X<\z> X<\G>
769 \b Match a word boundary
770 \B Match except at a word boundary
771 \A Match only at beginning of string
772 \Z Match only at end of string, or before newline at the end
773 \z Match only at end of string
774 \G Match only at pos() (e.g. at the end-of-match position
777 A word boundary (C<\b>) is a spot between two characters
778 that has a C<\w> on one side of it and a C<\W> on the other side
779 of it (in either order), counting the imaginary characters off the
780 beginning and end of the string as matching a C<\W>. (Within
781 character classes C<\b> represents backspace rather than a word
782 boundary, just as it normally does in any double-quoted string.)
783 The C<\A> and C<\Z> are just like "^" and "$", except that they
784 won't match multiple times when the C</m> modifier is used, while
785 "^" and "$" will match at every internal line boundary. To match
786 the actual end of the string and not ignore an optional trailing
788 X<\b> X<\A> X<\Z> X<\z> X</m>
790 The C<\G> assertion can be used to chain global matches (using
791 C<m//g>), as described in L<perlop/"Regexp Quote-Like Operators">.
792 It is also useful when writing C<lex>-like scanners, when you have
793 several patterns that you want to match against consequent substrings
794 of your string; see the previous reference. The actual location
795 where C<\G> will match can also be influenced by using C<pos()> as
796 an lvalue: see L<perlfunc/pos>. Note that the rule for zero-length
797 matches (see L</"Repeated Patterns Matching a Zero-length Substring">)
798 is modified somewhat, in that contents to the left of C<\G> are
799 not counted when determining the length of the match. Thus the following
800 will not match forever:
805 while ($string =~ /(.\G)/g) {
809 It will print 'A' and then terminate, as it considers the match to
810 be zero-width, and thus will not match at the same position twice in a
813 It is worth noting that C<\G> improperly used can result in an infinite
814 loop. Take care when using patterns that include C<\G> in an alternation.
816 Note also that C<s///> will refuse to overwrite part of a substitution
817 that has already been replaced; so for example this will stop after the
818 first iteration, rather than iterating its way backwards through the
824 print; # prints 1234X6789, not XXXXX6789
827 =head3 Capture groups
829 The bracketing construct C<( ... )> creates capture groups (also referred to as
830 capture buffers). To refer to the current contents of a group later on, within
831 the same pattern, use C<\g1> (or C<\g{1}>) for the first, C<\g2> (or C<\g{2}>)
832 for the second, and so on.
833 This is called a I<backreference>.
834 X<regex, capture buffer> X<regexp, capture buffer>
835 X<regex, capture group> X<regexp, capture group>
836 X<regular expression, capture buffer> X<backreference>
837 X<regular expression, capture group> X<backreference>
838 X<\g{1}> X<\g{-1}> X<\g{name}> X<relative backreference> X<named backreference>
839 X<named capture buffer> X<regular expression, named capture buffer>
840 X<named capture group> X<regular expression, named capture group>
841 X<%+> X<$+{name}> X<< \k<name> >>
842 There is no limit to the number of captured substrings that you may use.
843 Groups are numbered with the leftmost open parenthesis being number 1, etc. If
844 a group did not match, the associated backreference won't match either. (This
845 can happen if the group is optional, or in a different branch of an
847 You can omit the C<"g">, and write C<"\1">, etc, but there are some issues with
848 this form, described below.
850 You can also refer to capture groups relatively, by using a negative number, so
851 that C<\g-1> and C<\g{-1}> both refer to the immediately preceding capture
852 group, and C<\g-2> and C<\g{-2}> both refer to the group before it. For
859 \g{-1} # backref to group 3
860 \g{-3} # backref to group 1
864 would match the same as C</(Y) ( (X) \g3 \g1 )/x>. This allows you to
865 interpolate regexes into larger regexes and not have to worry about the
866 capture groups being renumbered.
868 You can dispense with numbers altogether and create named capture groups.
869 The notation is C<(?E<lt>I<name>E<gt>...)> to declare and C<\g{I<name>}> to
870 reference. (To be compatible with .Net regular expressions, C<\g{I<name>}> may
871 also be written as C<\k{I<name>}>, C<\kE<lt>I<name>E<gt>> or C<\k'I<name>'>.)
872 I<name> must not begin with a number, nor contain hyphens.
873 When different groups within the same pattern have the same name, any reference
874 to that name assumes the leftmost defined group. Named groups count in
875 absolute and relative numbering, and so can also be referred to by those
877 (It's possible to do things with named capture groups that would otherwise
880 Capture group contents are dynamically scoped and available to you outside the
881 pattern until the end of the enclosing block or until the next successful
882 match, whichever comes first. (See L<perlsyn/"Compound Statements">.)
883 You can refer to them by absolute number (using C<"$1"> instead of C<"\g1">,
884 etc); or by name via the C<%+> hash, using C<"$+{I<name>}">.
886 Braces are required in referring to named capture groups, but are optional for
887 absolute or relative numbered ones. Braces are safer when creating a regex by
888 concatenating smaller strings. For example if you have C<qr/$a$b/>, and C<$a>
889 contained C<"\g1">, and C<$b> contained C<"37">, you would get C</\g137/> which
890 is probably not what you intended.
892 The C<\g> and C<\k> notations were introduced in Perl 5.10.0. Prior to that
893 there were no named nor relative numbered capture groups. Absolute numbered
894 groups were referred to using C<\1>,
895 C<\2>, etc., and this notation is still
896 accepted (and likely always will be). But it leads to some ambiguities if
897 there are more than 9 capture groups, as C<\10> could mean either the tenth
898 capture group, or the character whose ordinal in octal is 010 (a backspace in
899 ASCII). Perl resolves this ambiguity by interpreting C<\10> as a backreference
900 only if at least 10 left parentheses have opened before it. Likewise C<\11> is
901 a backreference only if at least 11 left parentheses have opened before it.
902 And so on. C<\1> through C<\9> are always interpreted as backreferences.
903 There are several examples below that illustrate these perils. You can avoid
904 the ambiguity by always using C<\g{}> or C<\g> if you mean capturing groups;
905 and for octal constants always using C<\o{}>, or for C<\077> and below, using 3
906 digits padded with leading zeros, since a leading zero implies an octal
909 The C<\I<digit>> notation also works in certain circumstances outside
910 the pattern. See L</Warning on \1 Instead of $1> below for details.
914 s/^([^ ]*) *([^ ]*)/$2 $1/; # swap first two words
916 /(.)\g1/ # find first doubled char
917 and print "'$1' is the first doubled character\n";
919 /(?<char>.)\k<char>/ # ... a different way
920 and print "'$+{char}' is the first doubled character\n";
922 /(?'char'.)\g1/ # ... mix and match
923 and print "'$1' is the first doubled character\n";
925 if (/Time: (..):(..):(..)/) { # parse out values
931 /(.)(.)(.)(.)(.)(.)(.)(.)(.)\g10/ # \g10 is a backreference
932 /(.)(.)(.)(.)(.)(.)(.)(.)(.)\10/ # \10 is octal
933 /((.)(.)(.)(.)(.)(.)(.)(.)(.))\10/ # \10 is a backreference
934 /((.)(.)(.)(.)(.)(.)(.)(.)(.))\010/ # \010 is octal
936 $a = '(.)\1'; # Creates problems when concatenated.
937 $b = '(.)\g{1}'; # Avoids the problems.
938 "aa" =~ /${a}/; # True
939 "aa" =~ /${b}/; # True
940 "aa0" =~ /${a}0/; # False!
941 "aa0" =~ /${b}0/; # True
942 "aa\x08" =~ /${a}0/; # True!
943 "aa\x08" =~ /${b}0/; # False
945 Several special variables also refer back to portions of the previous
946 match. C<$+> returns whatever the last bracket match matched.
947 C<$&> returns the entire matched string. (At one point C<$0> did
948 also, but now it returns the name of the program.) C<$`> returns
949 everything before the matched string. C<$'> returns everything
950 after the matched string. And C<$^N> contains whatever was matched by
951 the most-recently closed group (submatch). C<$^N> can be used in
952 extended patterns (see below), for example to assign a submatch to a
954 X<$+> X<$^N> X<$&> X<$`> X<$'>
956 These special variables, like the C<%+> hash and the numbered match variables
957 (C<$1>, C<$2>, C<$3>, etc.) are dynamically scoped
958 until the end of the enclosing block or until the next successful
959 match, whichever comes first. (See L<perlsyn/"Compound Statements">.)
960 X<$+> X<$^N> X<$&> X<$`> X<$'>
961 X<$1> X<$2> X<$3> X<$4> X<$5> X<$6> X<$7> X<$8> X<$9>
963 B<NOTE>: Failed matches in Perl do not reset the match variables,
964 which makes it easier to write code that tests for a series of more
965 specific cases and remembers the best match.
967 B<WARNING>: If your code is to run on Perl 5.16 or earlier,
968 beware that once Perl sees that you need one of C<$&>, C<$`>, or
969 C<$'> anywhere in the program, it has to provide them for every
970 pattern match. This may substantially slow your program.
972 Perl uses the same mechanism to produce C<$1>, C<$2>, etc, so you also
973 pay a price for each pattern that contains capturing parentheses.
974 (To avoid this cost while retaining the grouping behaviour, use the
975 extended regular expression C<(?: ... )> instead.) But if you never
976 use C<$&>, C<$`> or C<$'>, then patterns I<without> capturing
977 parentheses will not be penalized. So avoid C<$&>, C<$'>, and C<$`>
978 if you can, but if you can't (and some algorithms really appreciate
979 them), once you've used them once, use them at will, because you've
980 already paid the price.
983 Perl 5.16 introduced a slightly more efficient mechanism that notes
984 separately whether each of C<$`>, C<$&>, and C<$'> have been seen, and
985 thus may only need to copy part of the string. Perl 5.20 introduced a
986 much more efficient copy-on-write mechanism which eliminates any slowdown.
988 As another workaround for this problem, Perl 5.10.0 introduced C<${^PREMATCH}>,
989 C<${^MATCH}> and C<${^POSTMATCH}>, which are equivalent to C<$`>, C<$&>
990 and C<$'>, B<except> that they are only guaranteed to be defined after a
991 successful match that was executed with the C</p> (preserve) modifier.
992 The use of these variables incurs no global performance penalty, unlike
993 their punctuation char equivalents, however at the trade-off that you
994 have to tell perl when you want to use them. As of Perl 5.20, these three
995 variables are equivalent to C<$`>, C<$&> and C<$'>, and C</p> is ignored.
998 =head2 Quoting metacharacters
1000 Backslashed metacharacters in Perl are alphanumeric, such as C<\b>,
1001 C<\w>, C<\n>. Unlike some other regular expression languages, there
1002 are no backslashed symbols that aren't alphanumeric. So anything
1003 that looks like \\, \(, \), \[, \], \{, or \} is always
1004 interpreted as a literal character, not a metacharacter. This was
1005 once used in a common idiom to disable or quote the special meanings
1006 of regular expression metacharacters in a string that you want to
1007 use for a pattern. Simply quote all non-"word" characters:
1009 $pattern =~ s/(\W)/\\$1/g;
1011 (If C<use locale> is set, then this depends on the current locale.)
1012 Today it is more common to use the quotemeta() function or the C<\Q>
1013 metaquoting escape sequence to disable all metacharacters' special
1016 /$unquoted\Q$quoted\E$unquoted/
1018 Beware that if you put literal backslashes (those not inside
1019 interpolated variables) between C<\Q> and C<\E>, double-quotish
1020 backslash interpolation may lead to confusing results. If you
1021 I<need> to use literal backslashes within C<\Q...\E>,
1022 consult L<perlop/"Gory details of parsing quoted constructs">.
1024 C<quotemeta()> and C<\Q> are fully described in L<perlfunc/quotemeta>.
1026 =head2 Extended Patterns
1028 Perl also defines a consistent extension syntax for features not
1029 found in standard tools like B<awk> and
1030 B<lex>. The syntax for most of these is a
1031 pair of parentheses with a question mark as the first thing within
1032 the parentheses. The character after the question mark indicates
1035 The stability of these extensions varies widely. Some have been
1036 part of the core language for many years. Others are experimental
1037 and may change without warning or be completely removed. Check
1038 the documentation on an individual feature to verify its current
1041 A question mark was chosen for this and for the minimal-matching
1042 construct because 1) question marks are rare in older regular
1043 expressions, and 2) whenever you see one, you should stop and
1044 "question" exactly what is going on. That's psychology....
1051 A comment. The text is ignored.
1052 Note that Perl closes
1053 the comment as soon as it sees a C<)>, so there is no way to put a literal
1054 C<)> in the comment. The pattern's closing delimiter must be escaped by
1055 a backslash if it appears in the comment.
1057 See L</E<sol>x> for another way to have comments in patterns.
1059 =item C<(?adlupimsx-imsx)>
1061 =item C<(?^alupimsx)>
1064 One or more embedded pattern-match modifiers, to be turned on (or
1065 turned off, if preceded by C<->) for the remainder of the pattern or
1066 the remainder of the enclosing pattern group (if any).
1068 This is particularly useful for dynamic patterns, such as those read in from a
1069 configuration file, taken from an argument, or specified in a table
1070 somewhere. Consider the case where some patterns want to be
1071 case-sensitive and some do not: The case-insensitive ones merely need to
1072 include C<(?i)> at the front of the pattern. For example:
1074 $pattern = "foobar";
1075 if ( /$pattern/i ) { }
1079 $pattern = "(?i)foobar";
1080 if ( /$pattern/ ) { }
1082 These modifiers are restored at the end of the enclosing group. For example,
1084 ( (?i) blah ) \s+ \g1
1086 will match C<blah> in any case, some spaces, and an exact (I<including the case>!)
1087 repetition of the previous word, assuming the C</x> modifier, and no C</i>
1088 modifier outside this group.
1090 These modifiers do not carry over into named subpatterns called in the
1091 enclosing group. In other words, a pattern such as C<((?i)(?&NAME))> does not
1092 change the case-sensitivity of the "NAME" pattern.
1094 Any of these modifiers can be set to apply globally to all regular
1095 expressions compiled within the scope of a C<use re>. See
1096 L<re/"'/flags' mode">.
1098 Starting in Perl 5.14, a C<"^"> (caret or circumflex accent) immediately
1099 after the C<"?"> is a shorthand equivalent to C<d-imsx>. Flags (except
1100 C<"d">) may follow the caret to override it.
1101 But a minus sign is not legal with it.
1103 Note that the C<a>, C<d>, C<l>, C<p>, and C<u> modifiers are special in
1104 that they can only be enabled, not disabled, and the C<a>, C<d>, C<l>, and
1105 C<u> modifiers are mutually exclusive: specifying one de-specifies the
1106 others, and a maximum of one (or two C<a>'s) may appear in the
1107 construct. Thus, for
1108 example, C<(?-p)> will warn when compiled under C<use warnings>;
1109 C<(?-d:...)> and C<(?dl:...)> are fatal errors.
1111 Note also that the C<p> modifier is special in that its presence
1112 anywhere in a pattern has a global effect.
1114 =item C<(?:pattern)>
1117 =item C<(?adluimsx-imsx:pattern)>
1119 =item C<(?^aluimsx:pattern)>
1122 This is for clustering, not capturing; it groups subexpressions like
1123 "()", but doesn't make backreferences as "()" does. So
1125 @fields = split(/\b(?:a|b|c)\b/)
1129 @fields = split(/\b(a|b|c)\b/)
1131 but doesn't spit out extra fields. It's also cheaper not to capture
1132 characters if you don't need to.
1134 Any letters between C<?> and C<:> act as flags modifiers as with
1135 C<(?adluimsx-imsx)>. For example,
1137 /(?s-i:more.*than).*million/i
1139 is equivalent to the more verbose
1141 /(?:(?s-i)more.*than).*million/i
1143 Starting in Perl 5.14, a C<"^"> (caret or circumflex accent) immediately
1144 after the C<"?"> is a shorthand equivalent to C<d-imsx>. Any positive
1145 flags (except C<"d">) may follow the caret, so
1153 The caret tells Perl that this cluster doesn't inherit the flags of any
1154 surrounding pattern, but uses the system defaults (C<d-imsx>),
1155 modified by any flags specified.
1157 The caret allows for simpler stringification of compiled regular
1158 expressions. These look like
1162 with any non-default flags appearing between the caret and the colon.
1163 A test that looks at such stringification thus doesn't need to have the
1164 system default flags hard-coded in it, just the caret. If new flags are
1165 added to Perl, the meaning of the caret's expansion will change to include
1166 the default for those flags, so the test will still work, unchanged.
1168 Specifying a negative flag after the caret is an error, as the flag is
1171 Mnemonic for C<(?^...)>: A fresh beginning since the usual use of a caret is
1172 to match at the beginning.
1174 =item C<(?|pattern)>
1175 X<(?|)> X<Branch reset>
1177 This is the "branch reset" pattern, which has the special property
1178 that the capture groups are numbered from the same starting point
1179 in each alternation branch. It is available starting from perl 5.10.0.
1181 Capture groups are numbered from left to right, but inside this
1182 construct the numbering is restarted for each branch.
1184 The numbering within each branch will be as normal, and any groups
1185 following this construct will be numbered as though the construct
1186 contained only one branch, that being the one with the most capture
1189 This construct is useful when you want to capture one of a
1190 number of alternative matches.
1192 Consider the following pattern. The numbers underneath show in
1193 which group the captured content will be stored.
1196 # before ---------------branch-reset----------- after
1197 / ( a ) (?| x ( y ) z | (p (q) r) | (t) u (v) ) ( z ) /x
1200 Be careful when using the branch reset pattern in combination with
1201 named captures. Named captures are implemented as being aliases to
1202 numbered groups holding the captures, and that interferes with the
1203 implementation of the branch reset pattern. If you are using named
1204 captures in a branch reset pattern, it's best to use the same names,
1205 in the same order, in each of the alternations:
1207 /(?| (?<a> x ) (?<b> y )
1208 | (?<a> z ) (?<b> w )) /x
1210 Not doing so may lead to surprises:
1212 "12" =~ /(?| (?<a> \d+ ) | (?<b> \D+))/x;
1213 say $+ {a}; # Prints '12'
1214 say $+ {b}; # *Also* prints '12'.
1216 The problem here is that both the group named C<< a >> and the group
1217 named C<< b >> are aliases for the group belonging to C<< $1 >>.
1219 =item Look-Around Assertions
1220 X<look-around assertion> X<lookaround assertion> X<look-around> X<lookaround>
1222 Look-around assertions are zero-width patterns which match a specific
1223 pattern without including it in C<$&>. Positive assertions match when
1224 their subpattern matches, negative assertions match when their subpattern
1225 fails. Look-behind matches text up to the current match position,
1226 look-ahead matches text following the current match position.
1230 =item C<(?=pattern)>
1231 X<(?=)> X<look-ahead, positive> X<lookahead, positive>
1233 A zero-width positive look-ahead assertion. For example, C</\w+(?=\t)/>
1234 matches a word followed by a tab, without including the tab in C<$&>.
1236 =item C<(?!pattern)>
1237 X<(?!)> X<look-ahead, negative> X<lookahead, negative>
1239 A zero-width negative look-ahead assertion. For example C</foo(?!bar)/>
1240 matches any occurrence of "foo" that isn't followed by "bar". Note
1241 however that look-ahead and look-behind are NOT the same thing. You cannot
1242 use this for look-behind.
1244 If you are looking for a "bar" that isn't preceded by a "foo", C</(?!foo)bar/>
1245 will not do what you want. That's because the C<(?!foo)> is just saying that
1246 the next thing cannot be "foo"--and it's not, it's a "bar", so "foobar" will
1247 match. Use look-behind instead (see below).
1249 =item C<(?<=pattern)> C<\K>
1250 X<(?<=)> X<look-behind, positive> X<lookbehind, positive> X<\K>
1252 A zero-width positive look-behind assertion. For example, C</(?<=\t)\w+/>
1253 matches a word that follows a tab, without including the tab in C<$&>.
1254 Works only for fixed-width look-behind.
1256 There is a special form of this construct, called C<\K> (available since
1257 Perl 5.10.0), which causes the
1258 regex engine to "keep" everything it had matched prior to the C<\K> and
1259 not include it in C<$&>. This effectively provides variable-length
1260 look-behind. The use of C<\K> inside of another look-around assertion
1261 is allowed, but the behaviour is currently not well defined.
1263 For various reasons C<\K> may be significantly more efficient than the
1264 equivalent C<< (?<=...) >> construct, and it is especially useful in
1265 situations where you want to efficiently remove something following
1266 something else in a string. For instance
1270 can be rewritten as the much more efficient
1274 =item C<(?<!pattern)>
1275 X<(?<!)> X<look-behind, negative> X<lookbehind, negative>
1277 A zero-width negative look-behind assertion. For example C</(?<!bar)foo/>
1278 matches any occurrence of "foo" that does not follow "bar". Works
1279 only for fixed-width look-behind.
1283 =item C<(?'NAME'pattern)>
1285 =item C<< (?<NAME>pattern) >>
1286 X<< (?<NAME>) >> X<(?'NAME')> X<named capture> X<capture>
1288 A named capture group. Identical in every respect to normal capturing
1289 parentheses C<()> but for the additional fact that the group
1290 can be referred to by name in various regular expression
1291 constructs (like C<\g{NAME}>) and can be accessed by name
1292 after a successful match via C<%+> or C<%->. See L<perlvar>
1293 for more details on the C<%+> and C<%-> hashes.
1295 If multiple distinct capture groups have the same name then the
1296 $+{NAME} will refer to the leftmost defined group in the match.
1298 The forms C<(?'NAME'pattern)> and C<< (?<NAME>pattern) >> are equivalent.
1300 B<NOTE:> While the notation of this construct is the same as the similar
1301 function in .NET regexes, the behavior is not. In Perl the groups are
1302 numbered sequentially regardless of being named or not. Thus in the
1307 $+{foo} will be the same as $2, and $3 will contain 'z' instead of
1308 the opposite which is what a .NET regex hacker might expect.
1310 Currently NAME is restricted to simple identifiers only.
1311 In other words, it must match C</^[_A-Za-z][_A-Za-z0-9]*\z/> or
1312 its Unicode extension (see L<utf8>),
1313 though it isn't extended by the locale (see L<perllocale>).
1315 B<NOTE:> In order to make things easier for programmers with experience
1316 with the Python or PCRE regex engines, the pattern C<< (?PE<lt>NAMEE<gt>pattern) >>
1317 may be used instead of C<< (?<NAME>pattern) >>; however this form does not
1318 support the use of single quotes as a delimiter for the name.
1320 =item C<< \k<NAME> >>
1322 =item C<< \k'NAME' >>
1324 Named backreference. Similar to numeric backreferences, except that
1325 the group is designated by name and not number. If multiple groups
1326 have the same name then it refers to the leftmost defined group in
1329 It is an error to refer to a name not defined by a C<< (?<NAME>) >>
1330 earlier in the pattern.
1332 Both forms are equivalent.
1334 B<NOTE:> In order to make things easier for programmers with experience
1335 with the Python or PCRE regex engines, the pattern C<< (?P=NAME) >>
1336 may be used instead of C<< \k<NAME> >>.
1338 =item C<(?{ code })>
1339 X<(?{})> X<regex, code in> X<regexp, code in> X<regular expression, code in>
1341 B<WARNING>: Using this feature safely requires that you understand its
1342 limitations. Code executed that has side effects may not perform identically
1343 from version to version due to the effect of future optimisations in the regex
1344 engine. For more information on this, see L</Embedded Code Execution
1347 This zero-width assertion executes any embedded Perl code. It always
1348 succeeds, and its return value is set as C<$^R>.
1350 In literal patterns, the code is parsed at the same time as the
1351 surrounding code. While within the pattern, control is passed temporarily
1352 back to the perl parser, until the logically-balancing closing brace is
1353 encountered. This is similar to the way that an array index expression in
1354 a literal string is handled, for example
1356 "abc$array[ 1 + f('[') + g()]def"
1358 In particular, braces do not need to be balanced:
1360 s/abc(?{ f('{'); })/def/
1362 Even in a pattern that is interpolated and compiled at run-time, literal
1363 code blocks will be compiled once, at perl compile time; the following
1367 my $qr = qr/(?{ BEGIN { print "A" } })/;
1369 /$foo$qr(?{ BEGIN { print "B" } })/;
1372 In patterns where the text of the code is derived from run-time
1373 information rather than appearing literally in a source code /pattern/,
1374 the code is compiled at the same time that the pattern is compiled, and
1375 for reasons of security, C<use re 'eval'> must be in scope. This is to
1376 stop user-supplied patterns containing code snippets from being
1379 In situations where you need to enable this with C<use re 'eval'>, you should
1380 also have taint checking enabled. Better yet, use the carefully
1381 constrained evaluation within a Safe compartment. See L<perlsec> for
1382 details about both these mechanisms.
1384 From the viewpoint of parsing, lexical variable scope and closures,
1388 behaves approximately like
1390 /AAA/ && do { BBB } && /CCC/
1394 qr/AAA(?{ BBB })CCC/
1396 behaves approximately like
1398 sub { /AAA/ && do { BBB } && /CCC/ }
1402 { my $i = 1; $r = qr/(?{ print $i })/ }
1406 Inside a C<(?{...})> block, C<$_> refers to the string the regular
1407 expression is matching against. You can also use C<pos()> to know what is
1408 the current position of matching within this string.
1410 The code block introduces a new scope from the perspective of lexical
1411 variable declarations, but B<not> from the perspective of C<local> and
1412 similar localizing behaviours. So later code blocks within the same
1413 pattern will still see the values which were localized in earlier blocks.
1414 These accumulated localizations are undone either at the end of a
1415 successful match, or if the assertion is backtracked (compare
1416 L<"Backtracking">). For example,
1420 (?{ $cnt = 0 }) # Initialize $cnt.
1424 local $cnt = $cnt + 1; # Update $cnt,
1425 # backtracking-safe.
1429 (?{ $res = $cnt }) # On success copy to
1430 # non-localized location.
1433 will initially increment C<$cnt> up to 8; then during backtracking, its
1434 value will be unwound back to 4, which is the value assigned to C<$res>.
1435 At the end of the regex execution, $cnt will be wound back to its initial
1438 This assertion may be used as the condition in a
1440 (?(condition)yes-pattern|no-pattern)
1442 switch. If I<not> used in this way, the result of evaluation of C<code>
1443 is put into the special variable C<$^R>. This happens immediately, so
1444 C<$^R> can be used from other C<(?{ code })> assertions inside the same
1447 The assignment to C<$^R> above is properly localized, so the old
1448 value of C<$^R> is restored if the assertion is backtracked; compare
1451 Note that the special variable C<$^N> is particularly useful with code
1452 blocks to capture the results of submatches in variables without having to
1453 keep track of the number of nested parentheses. For example:
1455 $_ = "The brown fox jumps over the lazy dog";
1456 /the (\S+)(?{ $color = $^N }) (\S+)(?{ $animal = $^N })/i;
1457 print "color = $color, animal = $animal\n";
1460 =item C<(??{ code })>
1462 X<regex, postponed> X<regexp, postponed> X<regular expression, postponed>
1464 B<WARNING>: Using this feature safely requires that you understand its
1465 limitations. Code executed that has side effects may not perform
1466 identically from version to version due to the effect of future
1467 optimisations in the regex engine. For more information on this, see
1468 L</Embedded Code Execution Frequency>.
1470 This is a "postponed" regular subexpression. It behaves in I<exactly> the
1471 same way as a C<(?{ code })> code block as described above, except that
1472 its return value, rather than being assigned to C<$^R>, is treated as a
1473 pattern, compiled if it's a string (or used as-is if its a qr// object),
1474 then matched as if it were inserted instead of this construct.
1476 During the matching of this sub-pattern, it has its own set of
1477 captures which are valid during the sub-match, but are discarded once
1478 control returns to the main pattern. For example, the following matches,
1479 with the inner pattern capturing "B" and matching "BB", while the outer
1480 pattern captures "A";
1482 my $inner = '(.)\1';
1483 "ABBA" =~ /^(.)(??{ $inner })\1/;
1484 print $1; # prints "A";
1486 Note that this means that there is no way for the inner pattern to refer
1487 to a capture group defined outside. (The code block itself can use C<$1>,
1488 etc., to refer to the enclosing pattern's capture groups.) Thus, although
1490 ('a' x 100)=~/(??{'(.)' x 100})/
1492 I<will> match, it will I<not> set $1 on exit.
1494 The following pattern matches a parenthesized group:
1499 (?> [^()]+ ) # Non-parens without backtracking
1501 (??{ $re }) # Group with matching parens
1507 L<C<(?I<PARNO>)>|/(?PARNO) (?-PARNO) (?+PARNO) (?R) (?0)>
1508 for a different, more efficient way to accomplish
1511 Executing a postponed regular expression 50 times without consuming any
1512 input string will result in a fatal error. The maximum depth is compiled
1513 into perl, so changing it requires a custom build.
1515 =item C<(?I<PARNO>)> C<(?-I<PARNO>)> C<(?+I<PARNO>)> C<(?R)> C<(?0)>
1516 X<(?PARNO)> X<(?1)> X<(?R)> X<(?0)> X<(?-1)> X<(?+1)> X<(?-PARNO)> X<(?+PARNO)>
1517 X<regex, recursive> X<regexp, recursive> X<regular expression, recursive>
1518 X<regex, relative recursion> X<GOSUB> X<GOSTART>
1520 Recursive subpattern. Treat the contents of a given capture buffer in the
1521 current pattern as an independent subpattern and attempt to match it at
1522 the current position in the string. Information about capture state from
1523 the caller for things like backreferences is available to the subpattern,
1524 but capture buffers set by the subpattern are not visible to the caller.
1526 Similar to C<(??{ code })> except that it does not involve executing any
1527 code or potentially compiling a returned pattern string; instead it treats
1528 the part of the current pattern contained within a specified capture group
1529 as an independent pattern that must match at the current position. Also
1530 different is the treatment of capture buffers, unlike C<(??{ code })>
1531 recursive patterns have access to their callers match state, so one can
1532 use backreferences safely.
1534 I<PARNO> is a sequence of digits (not starting with 0) whose value reflects
1535 the paren-number of the capture group to recurse to. C<(?R)> recurses to
1536 the beginning of the whole pattern. C<(?0)> is an alternate syntax for
1537 C<(?R)>. If I<PARNO> is preceded by a plus or minus sign then it is assumed
1538 to be relative, with negative numbers indicating preceding capture groups
1539 and positive ones following. Thus C<(?-1)> refers to the most recently
1540 declared group, and C<(?+1)> indicates the next group to be declared.
1541 Note that the counting for relative recursion differs from that of
1542 relative backreferences, in that with recursion unclosed groups B<are>
1545 The following pattern matches a function foo() which may contain
1546 balanced parentheses as the argument.
1548 $re = qr{ ( # paren group 1 (full function)
1550 ( # paren group 2 (parens)
1552 ( # paren group 3 (contents of parens)
1554 (?> [^()]+ ) # Non-parens without backtracking
1556 (?2) # Recurse to start of paren group 2
1564 If the pattern was used as follows
1566 'foo(bar(baz)+baz(bop))'=~/$re/
1567 and print "\$1 = $1\n",
1571 the output produced should be the following:
1573 $1 = foo(bar(baz)+baz(bop))
1574 $2 = (bar(baz)+baz(bop))
1575 $3 = bar(baz)+baz(bop)
1577 If there is no corresponding capture group defined, then it is a
1578 fatal error. Recursing deeper than 50 times without consuming any input
1579 string will also result in a fatal error. The maximum depth is compiled
1580 into perl, so changing it requires a custom build.
1582 The following shows how using negative indexing can make it
1583 easier to embed recursive patterns inside of a C<qr//> construct
1586 my $parens = qr/(\((?:[^()]++|(?-1))*+\))/;
1587 if (/foo $parens \s+ \+ \s+ bar $parens/x) {
1588 # do something here...
1591 B<Note> that this pattern does not behave the same way as the equivalent
1592 PCRE or Python construct of the same form. In Perl you can backtrack into
1593 a recursed group, in PCRE and Python the recursed into group is treated
1594 as atomic. Also, modifiers are resolved at compile time, so constructs
1595 like (?i:(?1)) or (?:(?i)(?1)) do not affect how the sub-pattern will
1601 Recurse to a named subpattern. Identical to C<(?I<PARNO>)> except that the
1602 parenthesis to recurse to is determined by name. If multiple parentheses have
1603 the same name, then it recurses to the leftmost.
1605 It is an error to refer to a name that is not declared somewhere in the
1608 B<NOTE:> In order to make things easier for programmers with experience
1609 with the Python or PCRE regex engines the pattern C<< (?P>NAME) >>
1610 may be used instead of C<< (?&NAME) >>.
1612 =item C<(?(condition)yes-pattern|no-pattern)>
1615 =item C<(?(condition)yes-pattern)>
1617 Conditional expression. Matches C<yes-pattern> if C<condition> yields
1618 a true value, matches C<no-pattern> otherwise. A missing pattern always
1621 C<(condition)> should be one of: 1) an integer in
1622 parentheses (which is valid if the corresponding pair of parentheses
1623 matched); 2) a look-ahead/look-behind/evaluate zero-width assertion; 3) a
1624 name in angle brackets or single quotes (which is valid if a group
1625 with the given name matched); or 4) the special symbol (R) (true when
1626 evaluated inside of recursion or eval). Additionally the R may be
1627 followed by a number, (which will be true when evaluated when recursing
1628 inside of the appropriate group), or by C<&NAME>, in which case it will
1629 be true only when evaluated during recursion in the named group.
1631 Here's a summary of the possible predicates:
1637 Checks if the numbered capturing group has matched something.
1639 =item (<NAME>) ('NAME')
1641 Checks if a group with the given name has matched something.
1643 =item (?=...) (?!...) (?<=...) (?<!...)
1645 Checks whether the pattern matches (or does not match, for the '!'
1650 Treats the return value of the code block as the condition.
1654 Checks if the expression has been evaluated inside of recursion.
1658 Checks if the expression has been evaluated while executing directly
1659 inside of the n-th capture group. This check is the regex equivalent of
1661 if ((caller(0))[3] eq 'subname') { ... }
1663 In other words, it does not check the full recursion stack.
1667 Similar to C<(R1)>, this predicate checks to see if we're executing
1668 directly inside of the leftmost group with a given name (this is the same
1669 logic used by C<(?&NAME)> to disambiguate). It does not check the full
1670 stack, but only the name of the innermost active recursion.
1674 In this case, the yes-pattern is never directly executed, and no
1675 no-pattern is allowed. Similar in spirit to C<(?{0})> but more efficient.
1676 See below for details.
1687 matches a chunk of non-parentheses, possibly included in parentheses
1690 A special form is the C<(DEFINE)> predicate, which never executes its
1691 yes-pattern directly, and does not allow a no-pattern. This allows one to
1692 define subpatterns which will be executed only by the recursion mechanism.
1693 This way, you can define a set of regular expression rules that can be
1694 bundled into any pattern you choose.
1696 It is recommended that for this usage you put the DEFINE block at the
1697 end of the pattern, and that you name any subpatterns defined within it.
1699 Also, it's worth noting that patterns defined this way probably will
1700 not be as efficient, as the optimizer is not very clever about
1703 An example of how this might be used is as follows:
1705 /(?<NAME>(?&NAME_PAT))(?<ADDR>(?&ADDRESS_PAT))
1708 (?<ADDRESS_PAT>....)
1711 Note that capture groups matched inside of recursion are not accessible
1712 after the recursion returns, so the extra layer of capturing groups is
1713 necessary. Thus C<$+{NAME_PAT}> would not be defined even though
1714 C<$+{NAME}> would be.
1716 Finally, keep in mind that subpatterns created inside a DEFINE block
1717 count towards the absolute and relative number of captures, so this:
1719 my @captures = "a" =~ /(.) # First capture
1721 (?<EXAMPLE> 1 ) # Second capture
1723 say scalar @captures;
1725 Will output 2, not 1. This is particularly important if you intend to
1726 compile the definitions with the C<qr//> operator, and later
1727 interpolate them in another pattern.
1729 =item C<< (?>pattern) >>
1730 X<backtrack> X<backtracking> X<atomic> X<possessive>
1732 An "independent" subexpression, one which matches the substring
1733 that a I<standalone> C<pattern> would match if anchored at the given
1734 position, and it matches I<nothing other than this substring>. This
1735 construct is useful for optimizations of what would otherwise be
1736 "eternal" matches, because it will not backtrack (see L<"Backtracking">).
1737 It may also be useful in places where the "grab all you can, and do not
1738 give anything back" semantic is desirable.
1740 For example: C<< ^(?>a*)ab >> will never match, since C<< (?>a*) >>
1741 (anchored at the beginning of string, as above) will match I<all>
1742 characters C<a> at the beginning of string, leaving no C<a> for
1743 C<ab> to match. In contrast, C<a*ab> will match the same as C<a+b>,
1744 since the match of the subgroup C<a*> is influenced by the following
1745 group C<ab> (see L<"Backtracking">). In particular, C<a*> inside
1746 C<a*ab> will match fewer characters than a standalone C<a*>, since
1747 this makes the tail match.
1749 C<< (?>pattern) >> does not disable backtracking altogether once it has
1750 matched. It is still possible to backtrack past the construct, but not
1751 into it. So C<< ((?>a*)|(?>b*))ar >> will still match "bar".
1753 An effect similar to C<< (?>pattern) >> may be achieved by writing
1754 C<(?=(pattern))\g{-1}>. This matches the same substring as a standalone
1755 C<a+>, and the following C<\g{-1}> eats the matched string; it therefore
1756 makes a zero-length assertion into an analogue of C<< (?>...) >>.
1757 (The difference between these two constructs is that the second one
1758 uses a capturing group, thus shifting ordinals of backreferences
1759 in the rest of a regular expression.)
1761 Consider this pattern:
1772 That will efficiently match a nonempty group with matching parentheses
1773 two levels deep or less. However, if there is no such group, it
1774 will take virtually forever on a long string. That's because there
1775 are so many different ways to split a long string into several
1776 substrings. This is what C<(.+)+> is doing, and C<(.+)+> is similar
1777 to a subpattern of the above pattern. Consider how the pattern
1778 above detects no-match on C<((()aaaaaaaaaaaaaaaaaa> in several
1779 seconds, but that each extra letter doubles this time. This
1780 exponential performance will make it appear that your program has
1781 hung. However, a tiny change to this pattern
1785 (?> [^()]+ ) # change x+ above to (?> x+ )
1792 which uses C<< (?>...) >> matches exactly when the one above does (verifying
1793 this yourself would be a productive exercise), but finishes in a fourth
1794 the time when used on a similar string with 1000000 C<a>s. Be aware,
1795 however, that, when this construct is followed by a
1796 quantifier, it currently triggers a warning message under
1797 the C<use warnings> pragma or B<-w> switch saying it
1798 C<"matches null string many times in regex">.
1800 On simple groups, such as the pattern C<< (?> [^()]+ ) >>, a comparable
1801 effect may be achieved by negative look-ahead, as in C<[^()]+ (?! [^()] )>.
1802 This was only 4 times slower on a string with 1000000 C<a>s.
1804 The "grab all you can, and do not give anything back" semantic is desirable
1805 in many situations where on the first sight a simple C<()*> looks like
1806 the correct solution. Suppose we parse text with comments being delimited
1807 by C<#> followed by some optional (horizontal) whitespace. Contrary to
1808 its appearance, C<#[ \t]*> I<is not> the correct subexpression to match
1809 the comment delimiter, because it may "give up" some whitespace if
1810 the remainder of the pattern can be made to match that way. The correct
1811 answer is either one of these:
1816 For example, to grab non-empty comments into $1, one should use either
1819 / (?> \# [ \t]* ) ( .+ ) /x;
1820 / \# [ \t]* ( [^ \t] .* ) /x;
1822 Which one you pick depends on which of these expressions better reflects
1823 the above specification of comments.
1825 In some literature this construct is called "atomic matching" or
1826 "possessive matching".
1828 Possessive quantifiers are equivalent to putting the item they are applied
1829 to inside of one of these constructs. The following equivalences apply:
1831 Quantifier Form Bracketing Form
1832 --------------- ---------------
1836 PAT{min,max}+ (?>PAT{min,max})
1840 See L<perlrecharclass/Extended Bracketed Character Classes>.
1844 =head2 Special Backtracking Control Verbs
1846 These special patterns are generally of the form C<(*VERB:ARG)>. Unless
1847 otherwise stated the ARG argument is optional; in some cases, it is
1850 Any pattern containing a special backtracking verb that allows an argument
1851 has the special behaviour that when executed it sets the current package's
1852 C<$REGERROR> and C<$REGMARK> variables. When doing so the following
1855 On failure, the C<$REGERROR> variable will be set to the ARG value of the
1856 verb pattern, if the verb was involved in the failure of the match. If the
1857 ARG part of the pattern was omitted, then C<$REGERROR> will be set to the
1858 name of the last C<(*MARK:NAME)> pattern executed, or to TRUE if there was
1859 none. Also, the C<$REGMARK> variable will be set to FALSE.
1861 On a successful match, the C<$REGERROR> variable will be set to FALSE, and
1862 the C<$REGMARK> variable will be set to the name of the last
1863 C<(*MARK:NAME)> pattern executed. See the explanation for the
1864 C<(*MARK:NAME)> verb below for more details.
1866 B<NOTE:> C<$REGERROR> and C<$REGMARK> are not magic variables like C<$1>
1867 and most other regex-related variables. They are not local to a scope, nor
1868 readonly, but instead are volatile package variables similar to C<$AUTOLOAD>.
1869 Use C<local> to localize changes to them to a specific scope if necessary.
1871 If a pattern does not contain a special backtracking verb that allows an
1872 argument, then C<$REGERROR> and C<$REGMARK> are not touched at all.
1876 =item Verbs that take an argument
1880 =item C<(*PRUNE)> C<(*PRUNE:NAME)>
1881 X<(*PRUNE)> X<(*PRUNE:NAME)>
1883 This zero-width pattern prunes the backtracking tree at the current point
1884 when backtracked into on failure. Consider the pattern C<A (*PRUNE) B>,
1885 where A and B are complex patterns. Until the C<(*PRUNE)> verb is reached,
1886 A may backtrack as necessary to match. Once it is reached, matching
1887 continues in B, which may also backtrack as necessary; however, should B
1888 not match, then no further backtracking will take place, and the pattern
1889 will fail outright at the current starting position.
1891 The following example counts all the possible matching strings in a
1892 pattern (without actually matching any of them).
1894 'aaab' =~ /a+b?(?{print "$&\n"; $count++})(*FAIL)/;
1895 print "Count=$count\n";
1910 If we add a C<(*PRUNE)> before the count like the following
1912 'aaab' =~ /a+b?(*PRUNE)(?{print "$&\n"; $count++})(*FAIL)/;
1913 print "Count=$count\n";
1915 we prevent backtracking and find the count of the longest matching string
1916 at each matching starting point like so:
1923 Any number of C<(*PRUNE)> assertions may be used in a pattern.
1925 See also C<< (?>pattern) >> and possessive quantifiers for other ways to
1926 control backtracking. In some cases, the use of C<(*PRUNE)> can be
1927 replaced with a C<< (?>pattern) >> with no functional difference; however,
1928 C<(*PRUNE)> can be used to handle cases that cannot be expressed using a
1929 C<< (?>pattern) >> alone.
1931 =item C<(*SKIP)> C<(*SKIP:NAME)>
1934 This zero-width pattern is similar to C<(*PRUNE)>, except that on
1935 failure it also signifies that whatever text that was matched leading up
1936 to the C<(*SKIP)> pattern being executed cannot be part of I<any> match
1937 of this pattern. This effectively means that the regex engine "skips" forward
1938 to this position on failure and tries to match again, (assuming that
1939 there is sufficient room to match).
1941 The name of the C<(*SKIP:NAME)> pattern has special significance. If a
1942 C<(*MARK:NAME)> was encountered while matching, then it is that position
1943 which is used as the "skip point". If no C<(*MARK)> of that name was
1944 encountered, then the C<(*SKIP)> operator has no effect. When used
1945 without a name the "skip point" is where the match point was when
1946 executing the (*SKIP) pattern.
1948 Compare the following to the examples in C<(*PRUNE)>; note the string
1951 'aaabaaab' =~ /a+b?(*SKIP)(?{print "$&\n"; $count++})(*FAIL)/;
1952 print "Count=$count\n";
1960 Once the 'aaab' at the start of the string has matched, and the C<(*SKIP)>
1961 executed, the next starting point will be where the cursor was when the
1962 C<(*SKIP)> was executed.
1964 =item C<(*MARK:NAME)> C<(*:NAME)>
1965 X<(*MARK)> X<(*MARK:NAME)> X<(*:NAME)>
1967 This zero-width pattern can be used to mark the point reached in a string
1968 when a certain part of the pattern has been successfully matched. This
1969 mark may be given a name. A later C<(*SKIP)> pattern will then skip
1970 forward to that point if backtracked into on failure. Any number of
1971 C<(*MARK)> patterns are allowed, and the NAME portion may be duplicated.
1973 In addition to interacting with the C<(*SKIP)> pattern, C<(*MARK:NAME)>
1974 can be used to "label" a pattern branch, so that after matching, the
1975 program can determine which branches of the pattern were involved in the
1978 When a match is successful, the C<$REGMARK> variable will be set to the
1979 name of the most recently executed C<(*MARK:NAME)> that was involved
1982 This can be used to determine which branch of a pattern was matched
1983 without using a separate capture group for each branch, which in turn
1984 can result in a performance improvement, as perl cannot optimize
1985 C</(?:(x)|(y)|(z))/> as efficiently as something like
1986 C</(?:x(*MARK:x)|y(*MARK:y)|z(*MARK:z))/>.
1988 When a match has failed, and unless another verb has been involved in
1989 failing the match and has provided its own name to use, the C<$REGERROR>
1990 variable will be set to the name of the most recently executed
1993 See L</(*SKIP)> for more details.
1995 As a shortcut C<(*MARK:NAME)> can be written C<(*:NAME)>.
1997 =item C<(*THEN)> C<(*THEN:NAME)>
1999 This is similar to the "cut group" operator C<::> from Perl 6. Like
2000 C<(*PRUNE)>, this verb always matches, and when backtracked into on
2001 failure, it causes the regex engine to try the next alternation in the
2002 innermost enclosing group (capturing or otherwise) that has alternations.
2003 The two branches of a C<(?(condition)yes-pattern|no-pattern)> do not
2004 count as an alternation, as far as C<(*THEN)> is concerned.
2006 Its name comes from the observation that this operation combined with the
2007 alternation operator (C<|>) can be used to create what is essentially a
2008 pattern-based if/then/else block:
2010 ( COND (*THEN) FOO | COND2 (*THEN) BAR | COND3 (*THEN) BAZ )
2012 Note that if this operator is used and NOT inside of an alternation then
2013 it acts exactly like the C<(*PRUNE)> operator.
2023 / ( A (*THEN) B | C ) /
2027 / ( A (*PRUNE) B | C ) /
2029 as after matching the A but failing on the B the C<(*THEN)> verb will
2030 backtrack and try C; but the C<(*PRUNE)> verb will simply fail.
2034 =item Verbs without an argument
2041 This is the Perl 6 "commit pattern" C<< <commit> >> or C<:::>. It's a
2042 zero-width pattern similar to C<(*SKIP)>, except that when backtracked
2043 into on failure it causes the match to fail outright. No further attempts
2044 to find a valid match by advancing the start pointer will occur again.
2047 'aaabaaab' =~ /a+b?(*COMMIT)(?{print "$&\n"; $count++})(*FAIL)/;
2048 print "Count=$count\n";
2055 In other words, once the C<(*COMMIT)> has been entered, and if the pattern
2056 does not match, the regex engine will not try any further matching on the
2059 =item C<(*FAIL)> C<(*F)>
2062 This pattern matches nothing and always fails. It can be used to force the
2063 engine to backtrack. It is equivalent to C<(?!)>, but easier to read. In
2064 fact, C<(?!)> gets optimised into C<(*FAIL)> internally.
2066 It is probably useful only when combined with C<(?{})> or C<(??{})>.
2071 This pattern matches nothing and causes the end of successful matching at
2072 the point at which the C<(*ACCEPT)> pattern was encountered, regardless of
2073 whether there is actually more to match in the string. When inside of a
2074 nested pattern, such as recursion, or in a subpattern dynamically generated
2075 via C<(??{})>, only the innermost pattern is ended immediately.
2077 If the C<(*ACCEPT)> is inside of capturing groups then the groups are
2078 marked as ended at the point at which the C<(*ACCEPT)> was encountered.
2081 'AB' =~ /(A (A|B(*ACCEPT)|C) D)(E)/x;
2083 will match, and C<$1> will be C<AB> and C<$2> will be C<B>, C<$3> will not
2084 be set. If another branch in the inner parentheses was matched, such as in the
2085 string 'ACDE', then the C<D> and C<E> would have to be matched as well.
2092 X<backtrack> X<backtracking>
2094 NOTE: This section presents an abstract approximation of regular
2095 expression behavior. For a more rigorous (and complicated) view of
2096 the rules involved in selecting a match among possible alternatives,
2097 see L<Combining RE Pieces>.
2099 A fundamental feature of regular expression matching involves the
2100 notion called I<backtracking>, which is currently used (when needed)
2101 by all regular non-possessive expression quantifiers, namely C<*>, C<*?>, C<+>,
2102 C<+?>, C<{n,m}>, and C<{n,m}?>. Backtracking is often optimized
2103 internally, but the general principle outlined here is valid.
2105 For a regular expression to match, the I<entire> regular expression must
2106 match, not just part of it. So if the beginning of a pattern containing a
2107 quantifier succeeds in a way that causes later parts in the pattern to
2108 fail, the matching engine backs up and recalculates the beginning
2109 part--that's why it's called backtracking.
2111 Here is an example of backtracking: Let's say you want to find the
2112 word following "foo" in the string "Food is on the foo table.":
2114 $_ = "Food is on the foo table.";
2115 if ( /\b(foo)\s+(\w+)/i ) {
2116 print "$2 follows $1.\n";
2119 When the match runs, the first part of the regular expression (C<\b(foo)>)
2120 finds a possible match right at the beginning of the string, and loads up
2121 $1 with "Foo". However, as soon as the matching engine sees that there's
2122 no whitespace following the "Foo" that it had saved in $1, it realizes its
2123 mistake and starts over again one character after where it had the
2124 tentative match. This time it goes all the way until the next occurrence
2125 of "foo". The complete regular expression matches this time, and you get
2126 the expected output of "table follows foo."
2128 Sometimes minimal matching can help a lot. Imagine you'd like to match
2129 everything between "foo" and "bar". Initially, you write something
2132 $_ = "The food is under the bar in the barn.";
2133 if ( /foo(.*)bar/ ) {
2137 Which perhaps unexpectedly yields:
2139 got <d is under the bar in the >
2141 That's because C<.*> was greedy, so you get everything between the
2142 I<first> "foo" and the I<last> "bar". Here it's more effective
2143 to use minimal matching to make sure you get the text between a "foo"
2144 and the first "bar" thereafter.
2146 if ( /foo(.*?)bar/ ) { print "got <$1>\n" }
2147 got <d is under the >
2149 Here's another example. Let's say you'd like to match a number at the end
2150 of a string, and you also want to keep the preceding part of the match.
2153 $_ = "I have 2 numbers: 53147";
2154 if ( /(.*)(\d*)/ ) { # Wrong!
2155 print "Beginning is <$1>, number is <$2>.\n";
2158 That won't work at all, because C<.*> was greedy and gobbled up the
2159 whole string. As C<\d*> can match on an empty string the complete
2160 regular expression matched successfully.
2162 Beginning is <I have 2 numbers: 53147>, number is <>.
2164 Here are some variants, most of which don't work:
2166 $_ = "I have 2 numbers: 53147";
2179 printf "%-12s ", $pat;
2181 print "<$1> <$2>\n";
2187 That will print out:
2189 (.*)(\d*) <I have 2 numbers: 53147> <>
2190 (.*)(\d+) <I have 2 numbers: 5314> <7>
2192 (.*?)(\d+) <I have > <2>
2193 (.*)(\d+)$ <I have 2 numbers: 5314> <7>
2194 (.*?)(\d+)$ <I have 2 numbers: > <53147>
2195 (.*)\b(\d+)$ <I have 2 numbers: > <53147>
2196 (.*\D)(\d+)$ <I have 2 numbers: > <53147>
2198 As you see, this can be a bit tricky. It's important to realize that a
2199 regular expression is merely a set of assertions that gives a definition
2200 of success. There may be 0, 1, or several different ways that the
2201 definition might succeed against a particular string. And if there are
2202 multiple ways it might succeed, you need to understand backtracking to
2203 know which variety of success you will achieve.
2205 When using look-ahead assertions and negations, this can all get even
2206 trickier. Imagine you'd like to find a sequence of non-digits not
2207 followed by "123". You might try to write that as
2210 if ( /^\D*(?!123)/ ) { # Wrong!
2211 print "Yup, no 123 in $_\n";
2214 But that isn't going to match; at least, not the way you're hoping. It
2215 claims that there is no 123 in the string. Here's a clearer picture of
2216 why that pattern matches, contrary to popular expectations:
2221 print "1: got $1\n" if $x =~ /^(ABC)(?!123)/;
2222 print "2: got $1\n" if $y =~ /^(ABC)(?!123)/;
2224 print "3: got $1\n" if $x =~ /^(\D*)(?!123)/;
2225 print "4: got $1\n" if $y =~ /^(\D*)(?!123)/;
2233 You might have expected test 3 to fail because it seems to a more
2234 general purpose version of test 1. The important difference between
2235 them is that test 3 contains a quantifier (C<\D*>) and so can use
2236 backtracking, whereas test 1 will not. What's happening is
2237 that you've asked "Is it true that at the start of $x, following 0 or more
2238 non-digits, you have something that's not 123?" If the pattern matcher had
2239 let C<\D*> expand to "ABC", this would have caused the whole pattern to
2242 The search engine will initially match C<\D*> with "ABC". Then it will
2243 try to match C<(?!123)> with "123", which fails. But because
2244 a quantifier (C<\D*>) has been used in the regular expression, the
2245 search engine can backtrack and retry the match differently
2246 in the hope of matching the complete regular expression.
2248 The pattern really, I<really> wants to succeed, so it uses the
2249 standard pattern back-off-and-retry and lets C<\D*> expand to just "AB" this
2250 time. Now there's indeed something following "AB" that is not
2251 "123". It's "C123", which suffices.
2253 We can deal with this by using both an assertion and a negation.
2254 We'll say that the first part in $1 must be followed both by a digit
2255 and by something that's not "123". Remember that the look-aheads
2256 are zero-width expressions--they only look, but don't consume any
2257 of the string in their match. So rewriting this way produces what
2258 you'd expect; that is, case 5 will fail, but case 6 succeeds:
2260 print "5: got $1\n" if $x =~ /^(\D*)(?=\d)(?!123)/;
2261 print "6: got $1\n" if $y =~ /^(\D*)(?=\d)(?!123)/;
2265 In other words, the two zero-width assertions next to each other work as though
2266 they're ANDed together, just as you'd use any built-in assertions: C</^$/>
2267 matches only if you're at the beginning of the line AND the end of the
2268 line simultaneously. The deeper underlying truth is that juxtaposition in
2269 regular expressions always means AND, except when you write an explicit OR
2270 using the vertical bar. C</ab/> means match "a" AND (then) match "b",
2271 although the attempted matches are made at different positions because "a"
2272 is not a zero-width assertion, but a one-width assertion.
2274 B<WARNING>: Particularly complicated regular expressions can take
2275 exponential time to solve because of the immense number of possible
2276 ways they can use backtracking to try for a match. For example, without
2277 internal optimizations done by the regular expression engine, this will
2278 take a painfully long time to run:
2280 'aaaaaaaaaaaa' =~ /((a{0,5}){0,5})*[c]/
2282 And if you used C<*>'s in the internal groups instead of limiting them
2283 to 0 through 5 matches, then it would take forever--or until you ran
2284 out of stack space. Moreover, these internal optimizations are not
2285 always applicable. For example, if you put C<{0,5}> instead of C<*>
2286 on the external group, no current optimization is applicable, and the
2287 match takes a long time to finish.
2289 A powerful tool for optimizing such beasts is what is known as an
2290 "independent group",
2291 which does not backtrack (see L</C<< (?>pattern) >>>). Note also that
2292 zero-length look-ahead/look-behind assertions will not backtrack to make
2293 the tail match, since they are in "logical" context: only
2294 whether they match is considered relevant. For an example
2295 where side-effects of look-ahead I<might> have influenced the
2296 following match, see L</C<< (?>pattern) >>>.
2298 =head2 Version 8 Regular Expressions
2299 X<regular expression, version 8> X<regex, version 8> X<regexp, version 8>
2301 In case you're not familiar with the "regular" Version 8 regex
2302 routines, here are the pattern-matching rules not described above.
2304 Any single character matches itself, unless it is a I<metacharacter>
2305 with a special meaning described here or above. You can cause
2306 characters that normally function as metacharacters to be interpreted
2307 literally by prefixing them with a "\" (e.g., "\." matches a ".", not any
2308 character; "\\" matches a "\"). This escape mechanism is also required
2309 for the character used as the pattern delimiter.
2311 A series of characters matches that series of characters in the target
2312 string, so the pattern C<blurfl> would match "blurfl" in the target
2315 You can specify a character class, by enclosing a list of characters
2316 in C<[]>, which will match any character from the list. If the
2317 first character after the "[" is "^", the class matches any character not
2318 in the list. Within a list, the "-" character specifies a
2319 range, so that C<a-z> represents all characters between "a" and "z",
2320 inclusive. If you want either "-" or "]" itself to be a member of a
2321 class, put it at the start of the list (possibly after a "^"), or
2322 escape it with a backslash. "-" is also taken literally when it is
2323 at the end of the list, just before the closing "]". (The
2324 following all specify the same class of three characters: C<[-az]>,
2325 C<[az-]>, and C<[a\-z]>. All are different from C<[a-z]>, which
2326 specifies a class containing twenty-six characters, even on EBCDIC-based
2327 character sets.) Also, if you try to use the character
2328 classes C<\w>, C<\W>, C<\s>, C<\S>, C<\d>, or C<\D> as endpoints of
2329 a range, the "-" is understood literally.
2331 Note also that the whole range idea is rather unportable between
2332 character sets--and even within character sets they may cause results
2333 you probably didn't expect. A sound principle is to use only ranges
2334 that begin from and end at either alphabetics of equal case ([a-e],
2335 [A-E]), or digits ([0-9]). Anything else is unsafe or unclear. If in
2336 doubt, spell out the character sets in full. Specifying the end points
2337 of the range using the C<\N{...}> syntax, using Unicode names or code
2338 points makes the range portable, but still likely not easily
2339 understandable to someone reading the code. For example,
2340 C<[\N{U+04}-\N{U+07}]> means to match the Unicode code points
2341 C<\N{U+04}>, C<\N{U+05}>, C<\N{U+06}>, and C<\N{U+07}>, whatever their
2342 native values may be on the platform.
2344 Characters may be specified using a metacharacter syntax much like that
2345 used in C: "\n" matches a newline, "\t" a tab, "\r" a carriage return,
2346 "\f" a form feed, etc. More generally, \I<nnn>, where I<nnn> is a string
2347 of three octal digits, matches the character whose coded character set value
2348 is I<nnn>. Similarly, \xI<nn>, where I<nn> are hexadecimal digits,
2349 matches the character whose ordinal is I<nn>. The expression \cI<x>
2350 matches the character control-I<x>. Finally, the "." metacharacter
2351 matches any character except "\n" (unless you use C</s>).
2353 You can specify a series of alternatives for a pattern using "|" to
2354 separate them, so that C<fee|fie|foe> will match any of "fee", "fie",
2355 or "foe" in the target string (as would C<f(e|i|o)e>). The
2356 first alternative includes everything from the last pattern delimiter
2357 ("(", "(?:", etc. or the beginning of the pattern) up to the first "|", and
2358 the last alternative contains everything from the last "|" to the next
2359 closing pattern delimiter. That's why it's common practice to include
2360 alternatives in parentheses: to minimize confusion about where they
2363 Alternatives are tried from left to right, so the first
2364 alternative found for which the entire expression matches, is the one that
2365 is chosen. This means that alternatives are not necessarily greedy. For
2366 example: when matching C<foo|foot> against "barefoot", only the "foo"
2367 part will match, as that is the first alternative tried, and it successfully
2368 matches the target string. (This might not seem important, but it is
2369 important when you are capturing matched text using parentheses.)
2371 Also remember that "|" is interpreted as a literal within square brackets,
2372 so if you write C<[fee|fie|foe]> you're really only matching C<[feio|]>.
2374 Within a pattern, you may designate subpatterns for later reference
2375 by enclosing them in parentheses, and you may refer back to the
2376 I<n>th subpattern later in the pattern using the metacharacter
2377 \I<n> or \gI<n>. Subpatterns are numbered based on the left to right order
2378 of their opening parenthesis. A backreference matches whatever
2379 actually matched the subpattern in the string being examined, not
2380 the rules for that subpattern. Therefore, C<(0|0x)\d*\s\g1\d*> will
2381 match "0x1234 0x4321", but not "0x1234 01234", because subpattern
2382 1 matched "0x", even though the rule C<0|0x> could potentially match
2383 the leading 0 in the second number.
2385 =head2 Warning on \1 Instead of $1
2387 Some people get too used to writing things like:
2389 $pattern =~ s/(\W)/\\\1/g;
2391 This is grandfathered (for \1 to \9) for the RHS of a substitute to avoid
2393 B<sed> addicts, but it's a dirty habit to get into. That's because in
2394 PerlThink, the righthand side of an C<s///> is a double-quoted string. C<\1> in
2395 the usual double-quoted string means a control-A. The customary Unix
2396 meaning of C<\1> is kludged in for C<s///>. However, if you get into the habit
2397 of doing that, you get yourself into trouble if you then add an C</e>
2400 s/(\d+)/ \1 + 1 /eg; # causes warning under -w
2406 You can't disambiguate that by saying C<\{1}000>, whereas you can fix it with
2407 C<${1}000>. The operation of interpolation should not be confused
2408 with the operation of matching a backreference. Certainly they mean two
2409 different things on the I<left> side of the C<s///>.
2411 =head2 Repeated Patterns Matching a Zero-length Substring
2413 B<WARNING>: Difficult material (and prose) ahead. This section needs a rewrite.
2415 Regular expressions provide a terse and powerful programming language. As
2416 with most other power tools, power comes together with the ability
2419 A common abuse of this power stems from the ability to make infinite
2420 loops using regular expressions, with something as innocuous as:
2422 'foo' =~ m{ ( o? )* }x;
2424 The C<o?> matches at the beginning of C<'foo'>, and since the position
2425 in the string is not moved by the match, C<o?> would match again and again
2426 because of the C<*> quantifier. Another common way to create a similar cycle
2427 is with the looping modifier C<//g>:
2429 @matches = ( 'foo' =~ m{ o? }xg );
2433 print "match: <$&>\n" while 'foo' =~ m{ o? }xg;
2435 or the loop implied by split().
2437 However, long experience has shown that many programming tasks may
2438 be significantly simplified by using repeated subexpressions that
2439 may match zero-length substrings. Here's a simple example being:
2441 @chars = split //, $string; # // is not magic in split
2442 ($whitewashed = $string) =~ s/()/ /g; # parens avoid magic s// /
2444 Thus Perl allows such constructs, by I<forcefully breaking
2445 the infinite loop>. The rules for this are different for lower-level
2446 loops given by the greedy quantifiers C<*+{}>, and for higher-level
2447 ones like the C</g> modifier or split() operator.
2449 The lower-level loops are I<interrupted> (that is, the loop is
2450 broken) when Perl detects that a repeated expression matched a
2451 zero-length substring. Thus
2453 m{ (?: NON_ZERO_LENGTH | ZERO_LENGTH )* }x;
2455 is made equivalent to
2457 m{ (?: NON_ZERO_LENGTH )* (?: ZERO_LENGTH )? }x;
2459 For example, this program
2466 (?{print "hello"}) # print hello whenever this
2468 (?=(b)) # zero-width assertion
2469 )* # any number of times
2480 Notice that "hello" is only printed once, as when Perl sees that the sixth
2481 iteration of the outermost C<(?:)*> matches a zero-length string, it stops
2484 The higher-level loops preserve an additional state between iterations:
2485 whether the last match was zero-length. To break the loop, the following
2486 match after a zero-length match is prohibited to have a length of zero.
2487 This prohibition interacts with backtracking (see L<"Backtracking">),
2488 and so the I<second best> match is chosen if the I<best> match is of
2496 results in C<< <><b><><a><><r><> >>. At each position of the string the best
2497 match given by non-greedy C<??> is the zero-length match, and the I<second
2498 best> match is what is matched by C<\w>. Thus zero-length matches
2499 alternate with one-character-long matches.
2501 Similarly, for repeated C<m/()/g> the second-best match is the match at the
2502 position one notch further in the string.
2504 The additional state of being I<matched with zero-length> is associated with
2505 the matched string, and is reset by each assignment to pos().
2506 Zero-length matches at the end of the previous match are ignored
2509 =head2 Combining RE Pieces
2511 Each of the elementary pieces of regular expressions which were described
2512 before (such as C<ab> or C<\Z>) could match at most one substring
2513 at the given position of the input string. However, in a typical regular
2514 expression these elementary pieces are combined into more complicated
2515 patterns using combining operators C<ST>, C<S|T>, C<S*> etc.
2516 (in these examples C<S> and C<T> are regular subexpressions).
2518 Such combinations can include alternatives, leading to a problem of choice:
2519 if we match a regular expression C<a|ab> against C<"abc">, will it match
2520 substring C<"a"> or C<"ab">? One way to describe which substring is
2521 actually matched is the concept of backtracking (see L<"Backtracking">).
2522 However, this description is too low-level and makes you think
2523 in terms of a particular implementation.
2525 Another description starts with notions of "better"/"worse". All the
2526 substrings which may be matched by the given regular expression can be
2527 sorted from the "best" match to the "worst" match, and it is the "best"
2528 match which is chosen. This substitutes the question of "what is chosen?"
2529 by the question of "which matches are better, and which are worse?".
2531 Again, for elementary pieces there is no such question, since at most
2532 one match at a given position is possible. This section describes the
2533 notion of better/worse for combining operators. In the description
2534 below C<S> and C<T> are regular subexpressions.
2540 Consider two possible matches, C<AB> and C<A'B'>, C<A> and C<A'> are
2541 substrings which can be matched by C<S>, C<B> and C<B'> are substrings
2542 which can be matched by C<T>.
2544 If C<A> is a better match for C<S> than C<A'>, C<AB> is a better
2547 If C<A> and C<A'> coincide: C<AB> is a better match than C<AB'> if
2548 C<B> is a better match for C<T> than C<B'>.
2552 When C<S> can match, it is a better match than when only C<T> can match.
2554 Ordering of two matches for C<S> is the same as for C<S>. Similar for
2555 two matches for C<T>.
2557 =item C<S{REPEAT_COUNT}>
2559 Matches as C<SSS...S> (repeated as many times as necessary).
2563 Matches as C<S{max}|S{max-1}|...|S{min+1}|S{min}>.
2565 =item C<S{min,max}?>
2567 Matches as C<S{min}|S{min+1}|...|S{max-1}|S{max}>.
2569 =item C<S?>, C<S*>, C<S+>
2571 Same as C<S{0,1}>, C<S{0,BIG_NUMBER}>, C<S{1,BIG_NUMBER}> respectively.
2573 =item C<S??>, C<S*?>, C<S+?>
2575 Same as C<S{0,1}?>, C<S{0,BIG_NUMBER}?>, C<S{1,BIG_NUMBER}?> respectively.
2579 Matches the best match for C<S> and only that.
2581 =item C<(?=S)>, C<(?<=S)>
2583 Only the best match for C<S> is considered. (This is important only if
2584 C<S> has capturing parentheses, and backreferences are used somewhere
2585 else in the whole regular expression.)
2587 =item C<(?!S)>, C<(?<!S)>
2589 For this grouping operator there is no need to describe the ordering, since
2590 only whether or not C<S> can match is important.
2592 =item C<(??{ EXPR })>, C<(?I<PARNO>)>
2594 The ordering is the same as for the regular expression which is
2595 the result of EXPR, or the pattern contained by capture group I<PARNO>.
2597 =item C<(?(condition)yes-pattern|no-pattern)>
2599 Recall that which of C<yes-pattern> or C<no-pattern> actually matches is
2600 already determined. The ordering of the matches is the same as for the
2601 chosen subexpression.
2605 The above recipes describe the ordering of matches I<at a given position>.
2606 One more rule is needed to understand how a match is determined for the
2607 whole regular expression: a match at an earlier position is always better
2608 than a match at a later position.
2610 =head2 Creating Custom RE Engines
2612 As of Perl 5.10.0, one can create custom regular expression engines. This
2613 is not for the faint of heart, as they have to plug in at the C level. See
2614 L<perlreapi> for more details.
2616 As an alternative, overloaded constants (see L<overload>) provide a simple
2617 way to extend the functionality of the RE engine, by substituting one
2618 pattern for another.
2620 Suppose that we want to enable a new RE escape-sequence C<\Y|> which
2621 matches at a boundary between whitespace characters and non-whitespace
2622 characters. Note that C<(?=\S)(?<!\S)|(?!\S)(?<=\S)> matches exactly
2623 at these positions, so we want to have each C<\Y|> in the place of the
2624 more complicated version. We can create a module C<customre> to do
2632 die "No argument to customre::import allowed" if @_;
2633 overload::constant 'qr' => \&convert;
2636 sub invalid { die "/$_[0]/: invalid escape '\\$_[1]'"}
2638 # We must also take care of not escaping the legitimate \\Y|
2639 # sequence, hence the presence of '\\' in the conversion rules.
2640 my %rules = ( '\\' => '\\\\',
2641 'Y|' => qr/(?=\S)(?<!\S)|(?!\S)(?<=\S)/ );
2647 { $rules{$1} or invalid($re,$1) }sgex;
2651 Now C<use customre> enables the new escape in constant regular
2652 expressions, i.e., those without any runtime variable interpolations.
2653 As documented in L<overload>, this conversion will work only over
2654 literal parts of regular expressions. For C<\Y|$re\Y|> the variable
2655 part of this regular expression needs to be converted explicitly
2656 (but only if the special meaning of C<\Y|> should be enabled inside $re):
2661 $re = customre::convert $re;
2664 =head2 Embedded Code Execution Frequency
2666 The exact rules for how often (??{}) and (?{}) are executed in a pattern
2667 are unspecified. In the case of a successful match you can assume that
2668 they DWIM and will be executed in left to right order the appropriate
2669 number of times in the accepting path of the pattern as would any other
2670 meta-pattern. How non-accepting pathways and match failures affect the
2671 number of times a pattern is executed is specifically unspecified and
2672 may vary depending on what optimizations can be applied to the pattern
2673 and is likely to change from version to version.
2677 "aaabcdeeeee"=~/a(?{print "a"})b(?{print "b"})cde/;
2679 the exact number of times "a" or "b" are printed out is unspecified for
2680 failure, but you may assume they will be printed at least once during
2681 a successful match, additionally you may assume that if "b" is printed,
2682 it will be preceded by at least one "a".
2684 In the case of branching constructs like the following:
2686 /a(b|(?{ print "a" }))c(?{ print "c" })/;
2688 you can assume that the input "ac" will output "ac", and that "abc"
2689 will output only "c".
2691 When embedded code is quantified, successful matches will call the
2692 code once for each matched iteration of the quantifier. For
2695 "good" =~ /g(?:o(?{print "o"}))*d/;
2697 will output "o" twice.
2699 =head2 PCRE/Python Support
2701 As of Perl 5.10.0, Perl supports several Python/PCRE-specific extensions
2702 to the regex syntax. While Perl programmers are encouraged to use the
2703 Perl-specific syntax, the following are also accepted:
2707 =item C<< (?PE<lt>NAMEE<gt>pattern) >>
2709 Define a named capture group. Equivalent to C<< (?<NAME>pattern) >>.
2711 =item C<< (?P=NAME) >>
2713 Backreference to a named capture group. Equivalent to C<< \g{NAME} >>.
2715 =item C<< (?P>NAME) >>
2717 Subroutine call to a named capture group. Equivalent to C<< (?&NAME) >>.
2723 Many regular expression constructs don't work on EBCDIC platforms.
2725 There are a number of issues with regard to case-insensitive matching
2726 in Unicode rules. See C<i> under L</Modifiers> above.
2728 This document varies from difficult to understand to completely
2729 and utterly opaque. The wandering prose riddled with jargon is
2730 hard to fathom in several places.
2732 This document needs a rewrite that separates the tutorial content
2733 from the reference content.
2741 L<perlop/"Regexp Quote-Like Operators">.
2743 L<perlop/"Gory details of parsing quoted constructs">.
2753 I<Mastering Regular Expressions> by Jeffrey Friedl, published
2754 by O'Reilly and Associates.