1PERLRE(1)              Perl Programmers Reference Guide              PERLRE(1)
2
3
4

NAME

6       perlre - Perl regular expressions
7

DESCRIPTION

9       This page describes the syntax of regular expressions in Perl.
10
11       If you haven't used regular expressions before, a tutorial introduction
12       is available in perlretut.  If you know just a little about them, a
13       quick-start introduction is available in perlrequick.
14
15       Except for "The Basics" section, this page assumes you are familiar
16       with regular expression basics, like what is a "pattern", what does it
17       look like, and how it is basically used.  For a reference on how they
18       are used, plus various examples of the same, see discussions of "m//",
19       "s///", "qr//" and "??" in "Regexp Quote-Like Operators" in perlop.
20
21       New in v5.22, "use re 'strict'" applies stricter rules than otherwise
22       when compiling regular expression patterns.  It can find things that,
23       while legal, may not be what you intended.
24
25   The Basics
26       Regular expressions are strings with the very particular syntax and
27       meaning described in this document and auxiliary documents referred to
28       by this one.  The strings are called "patterns".  Patterns are used to
29       determine if some other string, called the "target", has (or doesn't
30       have) the characteristics specified by the pattern.  We call this
31       "matching" the target string against the pattern.  Usually the match is
32       done by having the target be the first operand, and the pattern be the
33       second operand, of one of the two binary operators "=~" and "!~",
34       listed in "Binding Operators" in perlop; and the pattern will have been
35       converted from an ordinary string by one of the operators in "Regexp
36       Quote-Like Operators" in perlop, like so:
37
38        $foo =~ m/abc/
39
40       This evaluates to true if and only if the string in the variable $foo
41       contains somewhere in it, the sequence of characters "a", "b", then
42       "c".  (The "=~ m", or match operator, is described in
43       "m/PATTERN/msixpodualngc" in perlop.)
44
45       Patterns that aren't already stored in some variable must be
46       delimitted, at both ends, by delimitter characters.  These are often,
47       as in the example above, forward slashes, and the typical way a pattern
48       is written in documentation is with those slashes.  In most cases, the
49       delimitter is the same character, fore and aft, but there are a few
50       cases where a character looks like it has a mirror-image mate, where
51       the opening version is the beginning delimiter, and the closing one is
52       the ending delimiter, like
53
54        $foo =~ m<abc>
55
56       Most times, the pattern is evaluated in double-quotish context, but it
57       is possible to choose delimiters to force single-quotish, like
58
59        $foo =~ m'abc'
60
61       If the pattern contains its delimiter within it, that delimiter must be
62       escaped.  Prefixing it with a backslash (e.g., "/foo\/bar/") serves
63       this purpose.
64
65       Any single character in a pattern matches that same character in the
66       target string, unless the character is a metacharacter with a special
67       meaning described in this document.  A sequence of non-metacharacters
68       matches the same sequence in the target string, as we saw above with
69       "m/abc/".
70
71       Only a few characters (all of them being ASCII punctuation characters)
72       are metacharacters.  The most commonly used one is a dot ".", which
73       normally matches almost any character (including a dot itself).
74
75       You can cause characters that normally function as metacharacters to be
76       interpreted literally by prefixing them with a "\", just like the
77       pattern's delimiter must be escaped if it also occurs within the
78       pattern.  Thus, "\." matches just a literal dot, "." instead of its
79       normal meaning.  This means that the backslash is also a metacharacter,
80       so "\\" matches a single "\".  And a sequence that contains an escaped
81       metacharacter matches the same sequence (but without the escape) in the
82       target string.  So, the pattern "/blur\\fl/" would match any target
83       string that contains the sequence "blur\fl".
84
85       The metacharacter "|" is used to match one thing or another.  Thus
86
87        $foo =~ m/this|that/
88
89       is TRUE if and only if $foo contains either the sequence "this" or the
90       sequence "that".  Like all metacharacters, prefixing the "|" with a
91       backslash makes it match the plain punctuation character; in its case,
92       the VERTICAL LINE.
93
94        $foo =~ m/this\|that/
95
96       is TRUE if and only if $foo contains the sequence "this|that".
97
98       You aren't limited to just a single "|".
99
100        $foo =~ m/fee|fie|foe|fum/
101
102       is TRUE if and only if $foo contains any of those 4 sequences from the
103       children's story "Jack and the Beanstalk".
104
105       As you can see, the "|" binds less tightly than a sequence of ordinary
106       characters.  We can override this by using the grouping metacharacters,
107       the parentheses "(" and ")".
108
109        $foo =~ m/th(is|at) thing/
110
111       is TRUE if and only if $foo contains either the sequence "this thing"
112       or the sequence "that thing".  The portions of the string that match
113       the portions of the pattern enclosed in parentheses are normally made
114       available separately for use later in the pattern, substitution, or
115       program.  This is called "capturing", and it can get complicated.  See
116       "Capture groups".
117
118       The first alternative includes everything from the last pattern
119       delimiter ("(", "(?:" (described later), etc. or the beginning of the
120       pattern) up to the first "|", and the last alternative contains
121       everything from the last "|" to the next closing pattern delimiter.
122       That's why it's common practice to include alternatives in parentheses:
123       to minimize confusion about where they start and end.
124
125       Alternatives are tried from left to right, so the first alternative
126       found for which the entire expression matches, is the one that is
127       chosen. This means that alternatives are not necessarily greedy. For
128       example: when matching "foo|foot" against "barefoot", only the "foo"
129       part will match, as that is the first alternative tried, and it
130       successfully matches the target string. (This might not seem important,
131       but it is important when you are capturing matched text using
132       parentheses.)
133
134       Besides taking away the special meaning of a metacharacter, a prefixed
135       backslash changes some letter and digit characters away from matching
136       just themselves to instead have special meaning.  These are called
137       "escape sequences", and all such are described in perlrebackslash.  A
138       backslash sequence (of a letter or digit) that doesn't currently have
139       special meaning to Perl will raise a warning if warnings are enabled,
140       as those are reserved for potential future use.
141
142       One such sequence is "\b", which matches a boundary of some sort.
143       "\b{wb}" and a few others give specialized types of boundaries.  (They
144       are all described in detail starting at "\b{}, \b, \B{}, \B" in
145       perlrebackslash.)  Note that these don't match characters, but the
146       zero-width spaces between characters.  They are an example of a zero-
147       width assertion.  Consider again,
148
149        $foo =~ m/fee|fie|foe|fum/
150
151       It evaluates to TRUE if, besides those 4 words, any of the sequences
152       "feed", "field", "Defoe", "fume", and many others are in $foo.  By
153       judicious use of "\b" (or better (because it is designed to handle
154       natural language) "\b{wb}"), we can make sure that only the Giant's
155       words are matched:
156
157        $foo =~ m/\b(fee|fie|foe|fum)\b/
158        $foo =~ m/\b{wb}(fee|fie|foe|fum)\b{wb}/
159
160       The final example shows that the characters "{" and "}" are
161       metacharacters.
162
163       Another use for escape sequences is to specify characters that cannot
164       (or which you prefer not to) be written literally.  These are described
165       in detail in "Character Escapes" in perlrebackslash, but the next three
166       paragraphs briefly describe some of them.
167
168       Various control characters can be written in C language style: "\n"
169       matches a newline, "\t" a tab, "\r" a carriage return, "\f" a form
170       feed, etc.
171
172       More generally, "\nnn", where nnn is a string of three octal digits,
173       matches the character whose native code point is nnn.  You can easily
174       run into trouble if you don't have exactly three digits.  So always use
175       three, or since Perl 5.14, you can use "\o{...}" to specify any number
176       of octal digits.
177
178       Similarly, "\xnn", where nn are hexadecimal digits, matches the
179       character whose native ordinal is nn.  Again, not using exactly two
180       digits is a recipe for disaster, but you can use "\x{...}" to specify
181       any number of hex digits.
182
183       Besides being a metacharacter, the "." is an example of a "character
184       class", something that can match any single character of a given set of
185       them.  In its case, the set is just about all possible characters.
186       Perl predefines several character classes besides the "."; there is a
187       separate reference page about just these, perlrecharclass.
188
189       You can define your own custom character classes, by putting into your
190       pattern in the appropriate place(s), a list of all the characters you
191       want in the set.  You do this by enclosing the list within "[]" bracket
192       characters.  These are called "bracketed character classes" when we are
193       being precise, but often the word "bracketed" is dropped.  (Dropping it
194       usually doesn't cause confusion.)  This means that the "[" character is
195       another metacharacter.  It doesn't match anything just by itelf; it is
196       used only to tell Perl that what follows it is a bracketed character
197       class.  If you want to match a literal left square bracket, you must
198       escape it, like "\[".  The matching "]" is also a metacharacter; again
199       it doesn't match anything by itself, but just marks the end of your
200       custom class to Perl.  It is an example of a "sometimes metacharacter".
201       It isn't a metacharacter if there is no corresponding "[", and matches
202       its literal self:
203
204        print "]" =~ /]/;  # prints 1
205
206       The list of characters within the character class gives the set of
207       characters matched by the class.  "[abc]" matches a single "a" or "b"
208       or "c".  But if the first character after the "[" is "^", the class
209       matches any character not in the list.  Within a list, the "-"
210       character specifies a range of characters, so that "a-z" represents all
211       characters between "a" and "z", inclusive.  If you want either "-" or
212       "]" itself to be a member of a class, put it at the start of the list
213       (possibly after a "^"), or escape it with a backslash.  "-" is also
214       taken literally when it is at the end of the list, just before the
215       closing "]".  (The following all specify the same class of three
216       characters: "[-az]", "[az-]", and "[a\-z]".  All are different from
217       "[a-z]", which specifies a class containing twenty-six characters, even
218       on EBCDIC-based character sets.)
219
220       There is lots more to bracketed character classes; full details are in
221       "Bracketed Character Classes" in perlrecharclass.
222
223       Metacharacters
224
225       "The Basics" introduced some of the metacharacters.  This section gives
226       them all.  Most of them have the same meaning as in the egrep command.
227
228       Only the "\" is always a metacharacter.  The others are metacharacters
229       just sometimes.  The following tables lists all of them, summarizes
230       their use, and gives the contexts where they are metacharacters.
231       Outside those contexts or if prefixed by a "\", they match their
232       corresponding punctuation character.  In some cases, their meaning
233       varies depending on various pattern modifiers that alter the default
234       behaviors.  See "Modifiers".
235
236                   PURPOSE                                  WHERE
237        \   Escape the next character                    Always, except when
238                                                         escaped by another \
239        ^   Match the beginning of the string            Not in []
240              (or line, if /m is used)
241        ^   Complement the [] class                      At the beginning of []
242        .   Match any single character except newline    Not in []
243              (under /s, includes newline)
244        $   Match the end of the string                  Not in [], but can
245              (or before newline at the end of the       mean interpolate a
246              string; or before any newline if /m is     scalar
247              used)
248        |   Alternation                                  Not in []
249        ()  Grouping                                     Not in []
250        [   Start Bracketed Character class              Not in []
251        ]   End Bracketed Character class                Only in [], and
252                                                           not first
253        *   Matches the preceding element 0 or more      Not in []
254              times
255        +   Matches the preceding element 1 or more      Not in []
256              times
257        ?   Matches the preceding element 0 or 1         Not in []
258              times
259        {   Starts a sequence that gives number(s)       Not in []
260              of times the preceding element can be
261              matched
262        {   when following certain escape sequences
263              starts a modifier to the meaning of the
264              sequence
265        }   End sequence started by {
266        -   Indicates a range                            Only in [] interior
267
268       Notice that most of the metacharacters lose their special meaning when
269       they occur in a bracketed character class, except "^" has a different
270       meaning when it is at the beginning of such a class.  And "-" and "]"
271       are metacharacters only at restricted positions within bracketed
272       character classes; while "}" is a metacharacter only when closing a
273       special construct started by "{".
274
275       In double-quotish context, as is usually the case,  you need to be
276       careful about "$" and the non-metacharacter "@".  Those could
277       interpolate variables, which may or may not be what you intended.
278
279       These rules were designed for compactness of expression, rather than
280       legibility and maintainability.  The "/x and /xx" pattern modifiers
281       allow you to insert white space to improve readability.  And use of
282       "re 'strict'" adds extra checking to catch some typos that might
283       silently compile into something unintended.
284
285       By default, the "^" character is guaranteed to match only the beginning
286       of the string, the "$" character only the end (or before the newline at
287       the end), and Perl does certain optimizations with the assumption that
288       the string contains only one line.  Embedded newlines will not be
289       matched by "^" or "$".  You may, however, wish to treat a string as a
290       multi-line buffer, such that the "^" will match after any newline
291       within the string (except if the newline is the last character in the
292       string), and "$" will match before any newline.  At the cost of a
293       little more overhead, you can do this by using the ""/m"" modifier on
294       the pattern match operator.  (Older programs did this by setting $*,
295       but this option was removed in perl 5.10.)
296
297       To simplify multi-line substitutions, the "." character never matches a
298       newline unless you use the "/s" modifier, which in effect tells Perl to
299       pretend the string is a single line--even if it isn't.
300
301   Modifiers
302       Overview
303
304       The default behavior for matching can be changed, using various
305       modifiers.  Modifiers that relate to the interpretation of the pattern
306       are listed just below.  Modifiers that alter the way a pattern is used
307       by Perl are detailed in "Regexp Quote-Like Operators" in perlop and
308       "Gory details of parsing quoted constructs" in perlop.
309
310       "m" Treat the string being matched against as multiple lines.  That is,
311           change "^" and "$" from matching the start of the string's first
312           line and the end of its last line to matching the start and end of
313           each line within the string.
314
315       "s" Treat the string as single line.  That is, change "." to match any
316           character whatsoever, even a newline, which normally it would not
317           match.
318
319           Used together, as "/ms", they let the "." match any character
320           whatsoever, while still allowing "^" and "$" to match,
321           respectively, just after and just before newlines within the
322           string.
323
324       "i" Do case-insensitive pattern matching.  For example, "A" will match
325           "a" under "/i".
326
327           If locale matching rules are in effect, the case map is taken from
328           the current locale for code points less than 255, and from Unicode
329           rules for larger code points.  However, matches that would cross
330           the Unicode rules/non-Unicode rules boundary (ords 255/256) will
331           not succeed, unless the locale is a UTF-8 one.  See perllocale.
332
333           There are a number of Unicode characters that match a sequence of
334           multiple characters under "/i".  For example, "LATIN SMALL LIGATURE
335           FI" should match the sequence "fi".  Perl is not currently able to
336           do this when the multiple characters are in the pattern and are
337           split between groupings, or when one or more are quantified.  Thus
338
339            "\N{LATIN SMALL LIGATURE FI}" =~ /fi/i;          # Matches
340            "\N{LATIN SMALL LIGATURE FI}" =~ /[fi][fi]/i;    # Doesn't match!
341            "\N{LATIN SMALL LIGATURE FI}" =~ /fi*/i;         # Doesn't match!
342
343            # The below doesn't match, and it isn't clear what $1 and $2 would
344            # be even if it did!!
345            "\N{LATIN SMALL LIGATURE FI}" =~ /(f)(i)/i;      # Doesn't match!
346
347           Perl doesn't match multiple characters in a bracketed character
348           class unless the character that maps to them is explicitly
349           mentioned, and it doesn't match them at all if the character class
350           is inverted, which otherwise could be highly confusing.  See
351           "Bracketed Character Classes" in perlrecharclass, and "Negation" in
352           perlrecharclass.
353
354       "x" and "xx"
355           Extend your pattern's legibility by permitting whitespace and
356           comments.  Details in "/x and  /xx"
357
358       "p" Preserve the string matched such that "${^PREMATCH}", "${^MATCH}",
359           and "${^POSTMATCH}" are available for use after matching.
360
361           In Perl 5.20 and higher this is ignored. Due to a new copy-on-write
362           mechanism, "${^PREMATCH}", "${^MATCH}", and "${^POSTMATCH}" will be
363           available after the match regardless of the modifier.
364
365       "a", "d", "l", and "u"
366           These modifiers, all new in 5.14, affect which character-set rules
367           (Unicode, etc.) are used, as described below in "Character set
368           modifiers".
369
370       "n" Prevent the grouping metacharacters "()" from capturing. This
371           modifier, new in 5.22, will stop $1, $2, etc... from being filled
372           in.
373
374             "hello" =~ /(hi|hello)/;   # $1 is "hello"
375             "hello" =~ /(hi|hello)/n;  # $1 is undef
376
377           This is equivalent to putting "?:" at the beginning of every
378           capturing group:
379
380             "hello" =~ /(?:hi|hello)/; # $1 is undef
381
382           "/n" can be negated on a per-group basis. Alternatively, named
383           captures may still be used.
384
385             "hello" =~ /(?-n:(hi|hello))/n;   # $1 is "hello"
386             "hello" =~ /(?<greet>hi|hello)/n; # $1 is "hello", $+{greet} is
387                                               # "hello"
388
389       Other Modifiers
390           There are a number of flags that can be found at the end of regular
391           expression constructs that are not generic regular expression
392           flags, but apply to the operation being performed, like matching or
393           substitution ("m//" or "s///" respectively).
394
395           Flags described further in "Using regular expressions in Perl" in
396           perlretut are:
397
398             c  - keep the current position during repeated matching
399             g  - globally match the pattern repeatedly in the string
400
401           Substitution-specific modifiers described in
402           "s/PATTERN/REPLACEMENT/msixpodualngcer" in perlop are:
403
404             e  - evaluate the right-hand side as an expression
405             ee - evaluate the right side as a string then eval the result
406             o  - pretend to optimize your code, but actually introduce bugs
407             r  - perform non-destructive substitution and return the new value
408
409       Regular expression modifiers are usually written in documentation as
410       e.g., "the "/x" modifier", even though the delimiter in question might
411       not really be a slash.  The modifiers "/imnsxadlup" may also be
412       embedded within the regular expression itself using the "(?...)"
413       construct, see "Extended Patterns" below.
414
415       Details on some modifiers
416
417       Some of the modifiers require more explanation than given in the
418       "Overview" above.
419
420       "/x" and  "/xx"
421
422       A single "/x" tells the regular expression parser to ignore most
423       whitespace that is neither backslashed nor within a bracketed character
424       class.  You can use this to break up your regular expression into more
425       readable parts.  Also, the "#" character is treated as a metacharacter
426       introducing a comment that runs up to the pattern's closing delimiter,
427       or to the end of the current line if the pattern extends onto the next
428       line.  Hence, this is very much like an ordinary Perl code comment.
429       (You can include the closing delimiter within the comment only if you
430       precede it with a backslash, so be careful!)
431
432       Use of "/x" means that if you want real whitespace or "#" characters in
433       the pattern (outside a bracketed character class, which is unaffected
434       by "/x"), then you'll either have to escape them (using backslashes or
435       "\Q...\E") or encode them using octal, hex, or "\N{}" escapes.  It is
436       ineffective to try to continue a comment onto the next line by escaping
437       the "\n" with a backslash or "\Q".
438
439       You can use "(?#text)" to create a comment that ends earlier than the
440       end of the current line, but "text" also can't contain the closing
441       delimiter unless escaped with a backslash.
442
443       A common pitfall is to forget that "#" characters begin a comment under
444       "/x" and are not matched literally.  Just keep that in mind when trying
445       to puzzle out why a particular "/x" pattern isn't working as expected.
446
447       Starting in Perl v5.26, if the modifier has a second "x" within it, it
448       does everything that a single "/x" does, but additionally non-
449       backslashed SPACE and TAB characters within bracketed character classes
450       are also generally ignored, and hence can be added to make the classes
451       more readable.
452
453           / [d-e g-i 3-7]/xx
454           /[ ! @ " # $ % ^ & * () = ? <> ' ]/xx
455
456       may be easier to grasp than the squashed equivalents
457
458           /[d-eg-i3-7]/
459           /[!@"#$%^&*()=?<>']/
460
461       Taken together, these features go a long way towards making Perl's
462       regular expressions more readable.  Here's an example:
463
464           # Delete (most) C comments.
465           $program =~ s {
466               /\*     # Match the opening delimiter.
467               .*?     # Match a minimal number of characters.
468               \*/     # Match the closing delimiter.
469           } []gsx;
470
471       Note that anything inside a "\Q...\E" stays unaffected by "/x".  And
472       note that "/x" doesn't affect space interpretation within a single
473       multi-character construct.  For example in "\x{...}", regardless of the
474       "/x" modifier, there can be no spaces.  Same for a quantifier such as
475       "{3}" or "{5,}".  Similarly, "(?:...)" can't have a space between the
476       "(", "?", and ":".  Within any delimiters for such a construct, allowed
477       spaces are not affected by "/x", and depend on the construct.  For
478       example, "\x{...}" can't have spaces because hexadecimal numbers don't
479       have spaces in them.  But, Unicode properties can have spaces, so in
480       "\p{...}" there can be spaces that follow the Unicode rules, for which
481       see "Properties accessible through \p{} and \P{}" in perluniprops.
482
483       The set of characters that are deemed whitespace are those that Unicode
484       calls "Pattern White Space", namely:
485
486        U+0009 CHARACTER TABULATION
487        U+000A LINE FEED
488        U+000B LINE TABULATION
489        U+000C FORM FEED
490        U+000D CARRIAGE RETURN
491        U+0020 SPACE
492        U+0085 NEXT LINE
493        U+200E LEFT-TO-RIGHT MARK
494        U+200F RIGHT-TO-LEFT MARK
495        U+2028 LINE SEPARATOR
496        U+2029 PARAGRAPH SEPARATOR
497
498       Character set modifiers
499
500       "/d", "/u", "/a", and "/l", available starting in 5.14, are called the
501       character set modifiers; they affect the character set rules used for
502       the regular expression.
503
504       The "/d", "/u", and "/l" modifiers are not likely to be of much use to
505       you, and so you need not worry about them very much.  They exist for
506       Perl's internal use, so that complex regular expression data structures
507       can be automatically serialized and later exactly reconstituted,
508       including all their nuances.  But, since Perl can't keep a secret, and
509       there may be rare instances where they are useful, they are documented
510       here.
511
512       The "/a" modifier, on the other hand, may be useful.  Its purpose is to
513       allow code that is to work mostly on ASCII data to not have to concern
514       itself with Unicode.
515
516       Briefly, "/l" sets the character set to that of whatever Locale is in
517       effect at the time of the execution of the pattern match.
518
519       "/u" sets the character set to Unicode.
520
521       "/a" also sets the character set to Unicode, BUT adds several
522       restrictions for ASCII-safe matching.
523
524       "/d" is the old, problematic, pre-5.14 Default character set behavior.
525       Its only use is to force that old behavior.
526
527       At any given time, exactly one of these modifiers is in effect.  Their
528       existence allows Perl to keep the originally compiled behavior of a
529       regular expression, regardless of what rules are in effect when it is
530       actually executed.  And if it is interpolated into a larger regex, the
531       original's rules continue to apply to it, and only it.
532
533       The "/l" and "/u" modifiers are automatically selected for regular
534       expressions compiled within the scope of various pragmas, and we
535       recommend that in general, you use those pragmas instead of specifying
536       these modifiers explicitly.  For one thing, the modifiers affect only
537       pattern matching, and do not extend to even any replacement done,
538       whereas using the pragmas gives consistent results for all appropriate
539       operations within their scopes.  For example,
540
541        s/foo/\Ubar/il
542
543       will match "foo" using the locale's rules for case-insensitive
544       matching, but the "/l" does not affect how the "\U" operates.  Most
545       likely you want both of them to use locale rules.  To do this, instead
546       compile the regular expression within the scope of "use locale".  This
547       both implicitly adds the "/l", and applies locale rules to the "\U".
548       The lesson is to "use locale", and not "/l" explicitly.
549
550       Similarly, it would be better to use "use feature 'unicode_strings'"
551       instead of,
552
553        s/foo/\Lbar/iu
554
555       to get Unicode rules, as the "\L" in the former (but not necessarily
556       the latter) would also use Unicode rules.
557
558       More detail on each of the modifiers follows.  Most likely you don't
559       need to know this detail for "/l", "/u", and "/d", and can skip ahead
560       to /a.
561
562       /l
563
564       means to use the current locale's rules (see perllocale) when pattern
565       matching.  For example, "\w" will match the "word" characters of that
566       locale, and "/i" case-insensitive matching will match according to the
567       locale's case folding rules.  The locale used will be the one in effect
568       at the time of execution of the pattern match.  This may not be the
569       same as the compilation-time locale, and can differ from one match to
570       another if there is an intervening call of the setlocale() function.
571
572       Prior to v5.20, Perl did not support multi-byte locales.  Starting
573       then, UTF-8 locales are supported.  No other multi byte locales are
574       ever likely to be supported.  However, in all locales, one can have
575       code points above 255 and these will always be treated as Unicode no
576       matter what locale is in effect.
577
578       Under Unicode rules, there are a few case-insensitive matches that
579       cross the 255/256 boundary.  Except for UTF-8 locales in Perls v5.20
580       and later, these are disallowed under "/l".  For example, 0xFF (on
581       ASCII platforms) does not caselessly match the character at 0x178,
582       "LATIN CAPITAL LETTER Y WITH DIAERESIS", because 0xFF may not be "LATIN
583       SMALL LETTER Y WITH DIAERESIS" in the current locale, and Perl has no
584       way of knowing if that character even exists in the locale, much less
585       what code point it is.
586
587       In a UTF-8 locale in v5.20 and later, the only visible difference
588       between locale and non-locale in regular expressions should be tainting
589       (see perlsec).
590
591       This modifier may be specified to be the default by "use locale", but
592       see "Which character set modifier is in effect?".
593
594       /u
595
596       means to use Unicode rules when pattern matching.  On ASCII platforms,
597       this means that the code points between 128 and 255 take on their
598       Latin-1 (ISO-8859-1) meanings (which are the same as Unicode's).
599       (Otherwise Perl considers their meanings to be undefined.)  Thus, under
600       this modifier, the ASCII platform effectively becomes a Unicode
601       platform; and hence, for example, "\w" will match any of the more than
602       100_000 word characters in Unicode.
603
604       Unlike most locales, which are specific to a language and country pair,
605       Unicode classifies all the characters that are letters somewhere in the
606       world as "\w".  For example, your locale might not think that "LATIN
607       SMALL LETTER ETH" is a letter (unless you happen to speak Icelandic),
608       but Unicode does.  Similarly, all the characters that are decimal
609       digits somewhere in the world will match "\d"; this is hundreds, not
610       10, possible matches.  And some of those digits look like some of the
611       10 ASCII digits, but mean a different number, so a human could easily
612       think a number is a different quantity than it really is.  For example,
613       "BENGALI DIGIT FOUR" (U+09EA) looks very much like an "ASCII DIGIT
614       EIGHT" (U+0038).  And, "\d+", may match strings of digits that are a
615       mixture from different writing systems, creating a security issue.
616       "num()" in Unicode::UCD can be used to sort this out.  Or the "/a"
617       modifier can be used to force "\d" to match just the ASCII 0 through 9.
618
619       Also, under this modifier, case-insensitive matching works on the full
620       set of Unicode characters.  The "KELVIN SIGN", for example matches the
621       letters "k" and "K"; and "LATIN SMALL LIGATURE FF" matches the sequence
622       "ff", which, if you're not prepared, might make it look like a
623       hexadecimal constant, presenting another potential security issue.  See
624       <http://unicode.org/reports/tr36> for a detailed discussion of Unicode
625       security issues.
626
627       This modifier may be specified to be the default by "use feature
628       'unicode_strings", "use locale ':not_characters'", or "use 5.012" (or
629       higher), but see "Which character set modifier is in effect?".
630
631       /d
632
633       This modifier means to use the "Default" native rules of the platform
634       except when there is cause to use Unicode rules instead, as follows:
635
636       1.  the target string is encoded in UTF-8; or
637
638       2.  the pattern is encoded in UTF-8; or
639
640       3.  the pattern explicitly mentions a code point that is above 255 (say
641           by "\x{100}"); or
642
643       4.  the pattern uses a Unicode name ("\N{...}");  or
644
645       5.  the pattern uses a Unicode property ("\p{...}" or "\P{...}"); or
646
647       6.  the pattern uses a Unicode break ("\b{...}" or "\B{...}"); or
648
649       7.  the pattern uses ""(?[ ])""
650
651       Another mnemonic for this modifier is "Depends", as the rules actually
652       used depend on various things, and as a result you can get unexpected
653       results.  See "The "Unicode Bug"" in perlunicode.  The Unicode Bug has
654       become rather infamous, leading to yet another (printable) name for
655       this modifier, "Dodgy".
656
657       Unless the pattern or string are encoded in UTF-8, only ASCII
658       characters can match positively.
659
660       Here are some examples of how that works on an ASCII platform:
661
662        $str =  "\xDF";      # $str is not in UTF-8 format.
663        $str =~ /^\w/;       # No match, as $str isn't in UTF-8 format.
664        $str .= "\x{0e0b}";  # Now $str is in UTF-8 format.
665        $str =~ /^\w/;       # Match! $str is now in UTF-8 format.
666        chop $str;
667        $str =~ /^\w/;       # Still a match! $str remains in UTF-8 format.
668
669       This modifier is automatically selected by default when none of the
670       others are, so yet another name for it is "Default".
671
672       Because of the unexpected behaviors associated with this modifier, you
673       probably should only explicitly use it to maintain weird backward
674       compatibilities.
675
676       /a (and /aa)
677
678       This modifier stands for ASCII-restrict (or ASCII-safe).  This modifier
679       may be doubled-up to increase its effect.
680
681       When it appears singly, it causes the sequences "\d", "\s", "\w", and
682       the Posix character classes to match only in the ASCII range.  They
683       thus revert to their pre-5.6, pre-Unicode meanings.  Under "/a",  "\d"
684       always means precisely the digits "0" to "9"; "\s" means the five
685       characters "[ \f\n\r\t]", and starting in Perl v5.18, the vertical tab;
686       "\w" means the 63 characters "[A-Za-z0-9_]"; and likewise, all the
687       Posix classes such as "[[:print:]]" match only the appropriate ASCII-
688       range characters.
689
690       This modifier is useful for people who only incidentally use Unicode,
691       and who do not wish to be burdened with its complexities and security
692       concerns.
693
694       With "/a", one can write "\d" with confidence that it will only match
695       ASCII characters, and should the need arise to match beyond ASCII, you
696       can instead use "\p{Digit}" (or "\p{Word}" for "\w").  There are
697       similar "\p{...}" constructs that can match beyond ASCII both white
698       space (see "Whitespace" in perlrecharclass), and Posix classes (see
699       "POSIX Character Classes" in perlrecharclass).  Thus, this modifier
700       doesn't mean you can't use Unicode, it means that to get Unicode
701       matching you must explicitly use a construct ("\p{}", "\P{}") that
702       signals Unicode.
703
704       As you would expect, this modifier causes, for example, "\D" to mean
705       the same thing as "[^0-9]"; in fact, all non-ASCII characters match
706       "\D", "\S", and "\W".  "\b" still means to match at the boundary
707       between "\w" and "\W", using the "/a" definitions of them (similarly
708       for "\B").
709
710       Otherwise, "/a" behaves like the "/u" modifier, in that case-
711       insensitive matching uses Unicode rules; for example, "k" will match
712       the Unicode "\N{KELVIN SIGN}" under "/i" matching, and code points in
713       the Latin1 range, above ASCII will have Unicode rules when it comes to
714       case-insensitive matching.
715
716       To forbid ASCII/non-ASCII matches (like "k" with "\N{KELVIN SIGN}"),
717       specify the "a" twice, for example "/aai" or "/aia".  (The first
718       occurrence of "a" restricts the "\d", etc., and the second occurrence
719       adds the "/i" restrictions.)  But, note that code points outside the
720       ASCII range will use Unicode rules for "/i" matching, so the modifier
721       doesn't really restrict things to just ASCII; it just forbids the
722       intermixing of ASCII and non-ASCII.
723
724       To summarize, this modifier provides protection for applications that
725       don't wish to be exposed to all of Unicode.  Specifying it twice gives
726       added protection.
727
728       This modifier may be specified to be the default by "use re '/a'" or
729       "use re '/aa'".  If you do so, you may actually have occasion to use
730       the "/u" modifier explicitly if there are a few regular expressions
731       where you do want full Unicode rules (but even here, it's best if
732       everything were under feature "unicode_strings", along with the "use re
733       '/aa'").  Also see "Which character set modifier is in effect?".
734
735       Which character set modifier is in effect?
736
737       Which of these modifiers is in effect at any given point in a regular
738       expression depends on a fairly complex set of interactions.  These have
739       been designed so that in general you don't have to worry about it, but
740       this section gives the gory details.  As explained below in "Extended
741       Patterns" it is possible to explicitly specify modifiers that apply
742       only to portions of a regular expression.  The innermost always has
743       priority over any outer ones, and one applying to the whole expression
744       has priority over any of the default settings that are described in the
745       remainder of this section.
746
747       The "use re '/foo'" pragma can be used to set default modifiers
748       (including these) for regular expressions compiled within its scope.
749       This pragma has precedence over the other pragmas listed below that
750       also change the defaults.
751
752       Otherwise, "use locale" sets the default modifier to "/l"; and "use
753       feature 'unicode_strings", or "use 5.012" (or higher) set the default
754       to "/u" when not in the same scope as either "use locale" or "use
755       bytes".  ("use locale ':not_characters'" also sets the default to "/u",
756       overriding any plain "use locale".)  Unlike the mechanisms mentioned
757       above, these affect operations besides regular expressions pattern
758       matching, and so give more consistent results with other operators,
759       including using "\U", "\l", etc. in substitution replacements.
760
761       If none of the above apply, for backwards compatibility reasons, the
762       "/d" modifier is the one in effect by default.  As this can lead to
763       unexpected results, it is best to specify which other rule set should
764       be used.
765
766       Character set modifier behavior prior to Perl 5.14
767
768       Prior to 5.14, there were no explicit modifiers, but "/l" was implied
769       for regexes compiled within the scope of "use locale", and "/d" was
770       implied otherwise.  However, interpolating a regex into a larger regex
771       would ignore the original compilation in favor of whatever was in
772       effect at the time of the second compilation.  There were a number of
773       inconsistencies (bugs) with the "/d" modifier, where Unicode rules
774       would be used when inappropriate, and vice versa.  "\p{}" did not imply
775       Unicode rules, and neither did all occurrences of "\N{}", until 5.12.
776
777   Regular Expressions
778       Quantifiers
779
780       Quantifiers are used when a particular portion of a pattern needs to
781       match a certain number (or numbers) of times.  If there isn't a
782       quantifier the number of times to match is exactly one.  The following
783       standard quantifiers are recognized:
784
785           *           Match 0 or more times
786           +           Match 1 or more times
787           ?           Match 1 or 0 times
788           {n}         Match exactly n times
789           {n,}        Match at least n times
790           {n,m}       Match at least n but not more than m times
791
792       (If a non-escaped curly bracket occurs in a context other than one of
793       the quantifiers listed above, where it does not form part of a
794       backslashed sequence like "\x{...}", it is either a fatal syntax error,
795       or treated as a regular character, generally with a deprecation warning
796       raised.  To escape it, you can precede it with a backslash ("\{") or
797       enclose it within square brackets  ("[{]").  This change will allow for
798       future syntax extensions (like making the lower bound of a quantifier
799       optional), and better error checking of quantifiers).
800
801       The "*" quantifier is equivalent to "{0,}", the "+" quantifier to
802       "{1,}", and the "?" quantifier to "{0,1}".  n and m are limited to non-
803       negative integral values less than a preset limit defined when perl is
804       built.  This is usually 32766 on the most common platforms.  The actual
805       limit can be seen in the error message generated by code such as this:
806
807           $_ **= $_ , / {$_} / for 2 .. 42;
808
809       By default, a quantified subpattern is "greedy", that is, it will match
810       as many times as possible (given a particular starting location) while
811       still allowing the rest of the pattern to match.  If you want it to
812       match the minimum number of times possible, follow the quantifier with
813       a "?".  Note that the meanings don't change, just the "greediness":
814
815           *?        Match 0 or more times, not greedily
816           +?        Match 1 or more times, not greedily
817           ??        Match 0 or 1 time, not greedily
818           {n}?      Match exactly n times, not greedily (redundant)
819           {n,}?     Match at least n times, not greedily
820           {n,m}?    Match at least n but not more than m times, not greedily
821
822       Normally when a quantified subpattern does not allow the rest of the
823       overall pattern to match, Perl will backtrack. However, this behaviour
824       is sometimes undesirable. Thus Perl provides the "possessive"
825       quantifier form as well.
826
827        *+     Match 0 or more times and give nothing back
828        ++     Match 1 or more times and give nothing back
829        ?+     Match 0 or 1 time and give nothing back
830        {n}+   Match exactly n times and give nothing back (redundant)
831        {n,}+  Match at least n times and give nothing back
832        {n,m}+ Match at least n but not more than m times and give nothing back
833
834       For instance,
835
836          'aaaa' =~ /a++a/
837
838       will never match, as the "a++" will gobble up all the "a"'s in the
839       string and won't leave any for the remaining part of the pattern. This
840       feature can be extremely useful to give perl hints about where it
841       shouldn't backtrack. For instance, the typical "match a double-quoted
842       string" problem can be most efficiently performed when written as:
843
844          /"(?:[^"\\]++|\\.)*+"/
845
846       as we know that if the final quote does not match, backtracking will
847       not help. See the independent subexpression ""(?>pattern)"" for more
848       details; possessive quantifiers are just syntactic sugar for that
849       construct. For instance the above example could also be written as
850       follows:
851
852          /"(?>(?:(?>[^"\\]+)|\\.)*)"/
853
854       Note that the possessive quantifier modifier can not be be combined
855       with the non-greedy modifier. This is because it would make no sense.
856       Consider the follow equivalency table:
857
858           Illegal         Legal
859           ------------    ------
860           X??+            X{0}
861           X+?+            X{1}
862           X{min,max}?+    X{min}
863
864       Escape sequences
865
866       Because patterns are processed as double-quoted strings, the following
867       also work:
868
869        \t          tab                   (HT, TAB)
870        \n          newline               (LF, NL)
871        \r          return                (CR)
872        \f          form feed             (FF)
873        \a          alarm (bell)          (BEL)
874        \e          escape (think troff)  (ESC)
875        \cK         control char          (example: VT)
876        \x{}, \x00  character whose ordinal is the given hexadecimal number
877        \N{name}    named Unicode character or character sequence
878        \N{U+263D}  Unicode character     (example: FIRST QUARTER MOON)
879        \o{}, \000  character whose ordinal is the given octal number
880        \l          lowercase next char (think vi)
881        \u          uppercase next char (think vi)
882        \L          lowercase until \E (think vi)
883        \U          uppercase until \E (think vi)
884        \Q          quote (disable) pattern metacharacters until \E
885        \E          end either case modification or quoted section, think vi
886
887       Details are in "Quote and Quote-like Operators" in perlop.
888
889       Character Classes and other Special Escapes
890
891       In addition, Perl defines the following:
892
893        Sequence   Note    Description
894         [...]     [1]  Match a character according to the rules of the
895                          bracketed character class defined by the "...".
896                          Example: [a-z] matches "a" or "b" or "c" ... or "z"
897         [[:...:]] [2]  Match a character according to the rules of the POSIX
898                          character class "..." within the outer bracketed
899                          character class.  Example: [[:upper:]] matches any
900                          uppercase character.
901         (?[...])  [8]  Extended bracketed character class
902         \w        [3]  Match a "word" character (alphanumeric plus "_", plus
903                          other connector punctuation chars plus Unicode
904                          marks)
905         \W        [3]  Match a non-"word" character
906         \s        [3]  Match a whitespace character
907         \S        [3]  Match a non-whitespace character
908         \d        [3]  Match a decimal digit character
909         \D        [3]  Match a non-digit character
910         \pP       [3]  Match P, named property.  Use \p{Prop} for longer names
911         \PP       [3]  Match non-P
912         \X        [4]  Match Unicode "eXtended grapheme cluster"
913         \1        [5]  Backreference to a specific capture group or buffer.
914                          '1' may actually be any positive integer.
915         \g1       [5]  Backreference to a specific or previous group,
916         \g{-1}    [5]  The number may be negative indicating a relative
917                          previous group and may optionally be wrapped in
918                          curly brackets for safer parsing.
919         \g{name}  [5]  Named backreference
920         \k<name>  [5]  Named backreference
921         \K        [6]  Keep the stuff left of the \K, don't include it in $&
922         \N        [7]  Any character but \n.  Not affected by /s modifier
923         \v        [3]  Vertical whitespace
924         \V        [3]  Not vertical whitespace
925         \h        [3]  Horizontal whitespace
926         \H        [3]  Not horizontal whitespace
927         \R        [4]  Linebreak
928
929       [1] See "Bracketed Character Classes" in perlrecharclass for details.
930
931       [2] See "POSIX Character Classes" in perlrecharclass for details.
932
933       [3] See "Backslash sequences" in perlrecharclass for details.
934
935       [4] See "Misc" in perlrebackslash for details.
936
937       [5] See "Capture groups" below for details.
938
939       [6] See "Extended Patterns" below for details.
940
941       [7] Note that "\N" has two meanings.  When of the form "\N{NAME}", it
942           matches the character or character sequence whose name is "NAME";
943           and similarly when of the form "\N{U+hex}", it matches the
944           character whose Unicode code point is hex.  Otherwise it matches
945           any character but "\n".
946
947       [8] See "Extended Bracketed Character Classes" in perlrecharclass for
948           details.
949
950       Assertions
951
952       Besides "^" and "$", Perl defines the following zero-width assertions:
953
954        \b{}   Match at Unicode boundary of specified type
955        \B{}   Match where corresponding \b{} doesn't match
956        \b     Match a \w\W or \W\w boundary
957        \B     Match except at a \w\W or \W\w boundary
958        \A     Match only at beginning of string
959        \Z     Match only at end of string, or before newline at the end
960        \z     Match only at end of string
961        \G     Match only at pos() (e.g. at the end-of-match position
962               of prior m//g)
963
964       A Unicode boundary ("\b{}"), available starting in v5.22, is a spot
965       between two characters, or before the first character in the string, or
966       after the final character in the string where certain criteria defined
967       by Unicode are met.  See "\b{}, \b, \B{}, \B" in perlrebackslash for
968       details.
969
970       A word boundary ("\b") is a spot between two characters that has a "\w"
971       on one side of it and a "\W" on the other side of it (in either order),
972       counting the imaginary characters off the beginning and end of the
973       string as matching a "\W".  (Within character classes "\b" represents
974       backspace rather than a word boundary, just as it normally does in any
975       double-quoted string.)  The "\A" and "\Z" are just like "^" and "$",
976       except that they won't match multiple times when the "/m" modifier is
977       used, while "^" and "$" will match at every internal line boundary.  To
978       match the actual end of the string and not ignore an optional trailing
979       newline, use "\z".
980
981       The "\G" assertion can be used to chain global matches (using "m//g"),
982       as described in "Regexp Quote-Like Operators" in perlop.  It is also
983       useful when writing "lex"-like scanners, when you have several patterns
984       that you want to match against consequent substrings of your string;
985       see the previous reference.  The actual location where "\G" will match
986       can also be influenced by using "pos()" as an lvalue: see "pos" in
987       perlfunc. Note that the rule for zero-length matches (see "Repeated
988       Patterns Matching a Zero-length Substring") is modified somewhat, in
989       that contents to the left of "\G" are not counted when determining the
990       length of the match. Thus the following will not match forever:
991
992            my $string = 'ABC';
993            pos($string) = 1;
994            while ($string =~ /(.\G)/g) {
995                print $1;
996            }
997
998       It will print 'A' and then terminate, as it considers the match to be
999       zero-width, and thus will not match at the same position twice in a
1000       row.
1001
1002       It is worth noting that "\G" improperly used can result in an infinite
1003       loop. Take care when using patterns that include "\G" in an
1004       alternation.
1005
1006       Note also that "s///" will refuse to overwrite part of a substitution
1007       that has already been replaced; so for example this will stop after the
1008       first iteration, rather than iterating its way backwards through the
1009       string:
1010
1011           $_ = "123456789";
1012           pos = 6;
1013           s/.(?=.\G)/X/g;
1014           print;      # prints 1234X6789, not XXXXX6789
1015
1016       Capture groups
1017
1018       The grouping construct "( ... )" creates capture groups (also referred
1019       to as capture buffers). To refer to the current contents of a group
1020       later on, within the same pattern, use "\g1" (or "\g{1}") for the
1021       first, "\g2" (or "\g{2}") for the second, and so on.  This is called a
1022       backreference.
1023
1024
1025
1026
1027
1028
1029
1030
1031       There is no limit to the number of captured substrings that you may
1032       use.  Groups are numbered with the leftmost open parenthesis being
1033       number 1, etc.  If a group did not match, the associated backreference
1034       won't match either. (This can happen if the group is optional, or in a
1035       different branch of an alternation.)  You can omit the "g", and write
1036       "\1", etc, but there are some issues with this form, described below.
1037
1038       You can also refer to capture groups relatively, by using a negative
1039       number, so that "\g-1" and "\g{-1}" both refer to the immediately
1040       preceding capture group, and "\g-2" and "\g{-2}" both refer to the
1041       group before it.  For example:
1042
1043               /
1044                (Y)            # group 1
1045                (              # group 2
1046                   (X)         # group 3
1047                   \g{-1}      # backref to group 3
1048                   \g{-3}      # backref to group 1
1049                )
1050               /x
1051
1052       would match the same as "/(Y) ( (X) \g3 \g1 )/x".  This allows you to
1053       interpolate regexes into larger regexes and not have to worry about the
1054       capture groups being renumbered.
1055
1056       You can dispense with numbers altogether and create named capture
1057       groups.  The notation is "(?<name>...)" to declare and "\g{name}" to
1058       reference.  (To be compatible with .Net regular expressions, "\g{name}"
1059       may also be written as "\k{name}", "\k<name>" or "\k'name'".)  name
1060       must not begin with a number, nor contain hyphens.  When different
1061       groups within the same pattern have the same name, any reference to
1062       that name assumes the leftmost defined group.  Named groups count in
1063       absolute and relative numbering, and so can also be referred to by
1064       those numbers.  (It's possible to do things with named capture groups
1065       that would otherwise require "(??{})".)
1066
1067       Capture group contents are dynamically scoped and available to you
1068       outside the pattern until the end of the enclosing block or until the
1069       next successful match, whichever comes first.  (See "Compound
1070       Statements" in perlsyn.)  You can refer to them by absolute number
1071       (using "$1" instead of "\g1", etc); or by name via the "%+" hash, using
1072       "$+{name}".
1073
1074       Braces are required in referring to named capture groups, but are
1075       optional for absolute or relative numbered ones.  Braces are safer when
1076       creating a regex by concatenating smaller strings.  For example if you
1077       have "qr/$a$b/", and $a contained "\g1", and $b contained "37", you
1078       would get "/\g137/" which is probably not what you intended.
1079
1080       The "\g" and "\k" notations were introduced in Perl 5.10.0.  Prior to
1081       that there were no named nor relative numbered capture groups.
1082       Absolute numbered groups were referred to using "\1", "\2", etc., and
1083       this notation is still accepted (and likely always will be).  But it
1084       leads to some ambiguities if there are more than 9 capture groups, as
1085       "\10" could mean either the tenth capture group, or the character whose
1086       ordinal in octal is 010 (a backspace in ASCII).  Perl resolves this
1087       ambiguity by interpreting "\10" as a backreference only if at least 10
1088       left parentheses have opened before it.  Likewise "\11" is a
1089       backreference only if at least 11 left parentheses have opened before
1090       it.  And so on.  "\1" through "\9" are always interpreted as
1091       backreferences.  There are several examples below that illustrate these
1092       perils.  You can avoid the ambiguity by always using "\g{}" or "\g" if
1093       you mean capturing groups; and for octal constants always using "\o{}",
1094       or for "\077" and below, using 3 digits padded with leading zeros,
1095       since a leading zero implies an octal constant.
1096
1097       The "\digit" notation also works in certain circumstances outside the
1098       pattern.  See "Warning on \1 Instead of $1" below for details.
1099
1100       Examples:
1101
1102           s/^([^ ]*) *([^ ]*)/$2 $1/;     # swap first two words
1103
1104           /(.)\g1/                        # find first doubled char
1105                and print "'$1' is the first doubled character\n";
1106
1107           /(?<char>.)\k<char>/            # ... a different way
1108                and print "'$+{char}' is the first doubled character\n";
1109
1110           /(?'char'.)\g1/                 # ... mix and match
1111                and print "'$1' is the first doubled character\n";
1112
1113           if (/Time: (..):(..):(..)/) {   # parse out values
1114               $hours = $1;
1115               $minutes = $2;
1116               $seconds = $3;
1117           }
1118
1119           /(.)(.)(.)(.)(.)(.)(.)(.)(.)\g10/   # \g10 is a backreference
1120           /(.)(.)(.)(.)(.)(.)(.)(.)(.)\10/    # \10 is octal
1121           /((.)(.)(.)(.)(.)(.)(.)(.)(.))\10/  # \10 is a backreference
1122           /((.)(.)(.)(.)(.)(.)(.)(.)(.))\010/ # \010 is octal
1123
1124           $a = '(.)\1';        # Creates problems when concatenated.
1125           $b = '(.)\g{1}';     # Avoids the problems.
1126           "aa" =~ /${a}/;      # True
1127           "aa" =~ /${b}/;      # True
1128           "aa0" =~ /${a}0/;    # False!
1129           "aa0" =~ /${b}0/;    # True
1130           "aa\x08" =~ /${a}0/;  # True!
1131           "aa\x08" =~ /${b}0/;  # False
1132
1133       Several special variables also refer back to portions of the previous
1134       match.  $+ returns whatever the last bracket match matched.  $& returns
1135       the entire matched string.  (At one point $0 did also, but now it
1136       returns the name of the program.)  "$`" returns everything before the
1137       matched string.  "$'" returns everything after the matched string. And
1138       $^N contains whatever was matched by the most-recently closed group
1139       (submatch). $^N can be used in extended patterns (see below), for
1140       example to assign a submatch to a variable.
1141
1142       These special variables, like the "%+" hash and the numbered match
1143       variables ($1, $2, $3, etc.) are dynamically scoped until the end of
1144       the enclosing block or until the next successful match, whichever comes
1145       first.  (See "Compound Statements" in perlsyn.)
1146
1147       NOTE: Failed matches in Perl do not reset the match variables, which
1148       makes it easier to write code that tests for a series of more specific
1149       cases and remembers the best match.
1150
1151       WARNING: If your code is to run on Perl 5.16 or earlier, beware that
1152       once Perl sees that you need one of $&, "$`", or "$'" anywhere in the
1153       program, it has to provide them for every pattern match.  This may
1154       substantially slow your program.
1155
1156       Perl uses the same mechanism to produce $1, $2, etc, so you also pay a
1157       price for each pattern that contains capturing parentheses.  (To avoid
1158       this cost while retaining the grouping behaviour, use the extended
1159       regular expression "(?: ... )" instead.)  But if you never use $&, "$`"
1160       or "$'", then patterns without capturing parentheses will not be
1161       penalized.  So avoid $&, "$'", and "$`" if you can, but if you can't
1162       (and some algorithms really appreciate them), once you've used them
1163       once, use them at will, because you've already paid the price.
1164
1165       Perl 5.16 introduced a slightly more efficient mechanism that notes
1166       separately whether each of "$`", $&, and "$'" have been seen, and thus
1167       may only need to copy part of the string.  Perl 5.20 introduced a much
1168       more efficient copy-on-write mechanism which eliminates any slowdown.
1169
1170       As another workaround for this problem, Perl 5.10.0 introduced
1171       "${^PREMATCH}", "${^MATCH}" and "${^POSTMATCH}", which are equivalent
1172       to "$`", $& and "$'", except that they are only guaranteed to be
1173       defined after a successful match that was executed with the "/p"
1174       (preserve) modifier.  The use of these variables incurs no global
1175       performance penalty, unlike their punctuation character equivalents,
1176       however at the trade-off that you have to tell perl when you want to
1177       use them.  As of Perl 5.20, these three variables are equivalent to
1178       "$`", $& and "$'", and "/p" is ignored.
1179
1180   Quoting metacharacters
1181       Backslashed metacharacters in Perl are alphanumeric, such as "\b",
1182       "\w", "\n".  Unlike some other regular expression languages, there are
1183       no backslashed symbols that aren't alphanumeric.  So anything that
1184       looks like "\\", "\(", "\)", "\[", "\]", "\{", or "\}" is always
1185       interpreted as a literal character, not a metacharacter.  This was once
1186       used in a common idiom to disable or quote the special meanings of
1187       regular expression metacharacters in a string that you want to use for
1188       a pattern. Simply quote all non-"word" characters:
1189
1190           $pattern =~ s/(\W)/\\$1/g;
1191
1192       (If "use locale" is set, then this depends on the current locale.)
1193       Today it is more common to use the "quotemeta()" function or the "\Q"
1194       metaquoting escape sequence to disable all metacharacters' special
1195       meanings like this:
1196
1197           /$unquoted\Q$quoted\E$unquoted/
1198
1199       Beware that if you put literal backslashes (those not inside
1200       interpolated variables) between "\Q" and "\E", double-quotish backslash
1201       interpolation may lead to confusing results.  If you need to use
1202       literal backslashes within "\Q...\E", consult "Gory details of parsing
1203       quoted constructs" in perlop.
1204
1205       "quotemeta()" and "\Q" are fully described in "quotemeta" in perlfunc.
1206
1207   Extended Patterns
1208       Perl also defines a consistent extension syntax for features not found
1209       in standard tools like awk and lex.  The syntax for most of these is a
1210       pair of parentheses with a question mark as the first thing within the
1211       parentheses.  The character after the question mark indicates the
1212       extension.
1213
1214       A question mark was chosen for this and for the minimal-matching
1215       construct because 1) question marks are rare in older regular
1216       expressions, and 2) whenever you see one, you should stop and
1217       "question" exactly what is going on.  That's psychology....
1218
1219       "(?#text)"
1220           A comment.  The text is ignored.  Note that Perl closes the comment
1221           as soon as it sees a ")", so there is no way to put a literal ")"
1222           in the comment.  The pattern's closing delimiter must be escaped by
1223           a backslash if it appears in the comment.
1224
1225           See "/x" for another way to have comments in patterns.
1226
1227           Note that a comment can go just about anywhere, except in the
1228           middle of an escape sequence.   Examples:
1229
1230            qr/foo(?#comment)bar/'  # Matches 'foobar'
1231
1232            # The pattern below matches 'abcd', 'abccd', or 'abcccd'
1233            qr/abc(?#comment between literal and its quantifier){1,3}d/
1234
1235            # The pattern below generates a syntax error, because the '\p' must
1236            # be followed immediately by a '{'.
1237            qr/\p(?#comment between \p and its property name){Any}/
1238
1239            # The pattern below generates a syntax error, because the initial
1240            # '\(' is a literal opening parenthesis, and so there is nothing
1241            # for the  closing ')' to match
1242            qr/\(?#the backslash means this isn't a comment)p{Any}/
1243
1244       "(?adlupimnsx-imnsx)"
1245       "(?^alupimnsx)"
1246           One or more embedded pattern-match modifiers, to be turned on (or
1247           turned off if preceded by "-") for the remainder of the pattern or
1248           the remainder of the enclosing pattern group (if any).
1249
1250           This is particularly useful for dynamically-generated patterns,
1251           such as those read in from a configuration file, taken from an
1252           argument, or specified in a table somewhere.  Consider the case
1253           where some patterns want to be case-sensitive and some do not:  The
1254           case-insensitive ones merely need to include "(?i)" at the front of
1255           the pattern.  For example:
1256
1257               $pattern = "foobar";
1258               if ( /$pattern/i ) { }
1259
1260               # more flexible:
1261
1262               $pattern = "(?i)foobar";
1263               if ( /$pattern/ ) { }
1264
1265           These modifiers are restored at the end of the enclosing group. For
1266           example,
1267
1268               ( (?i) blah ) \s+ \g1
1269
1270           will match "blah" in any case, some spaces, and an exact (including
1271           the case!)  repetition of the previous word, assuming the "/x"
1272           modifier, and no "/i" modifier outside this group.
1273
1274           These modifiers do not carry over into named subpatterns called in
1275           the enclosing group. In other words, a pattern such as
1276           "((?i)(?&NAME))" does not change the case-sensitivity of the "NAME"
1277           pattern.
1278
1279           A modifier is overridden by later occurrences of this construct in
1280           the same scope containing the same modifier, so that
1281
1282               /((?im)foo(?-m)bar)/
1283
1284           matches all of "foobar" case insensitively, but uses "/m" rules for
1285           only the "foo" portion.  The "a" flag overrides "aa" as well;
1286           likewise "aa" overrides "a".  The same goes for "x" and "xx".
1287           Hence, in
1288
1289               /(?-x)foo/xx
1290
1291           both "/x" and "/xx" are turned off during matching "foo".  And in
1292
1293               /(?x)foo/x
1294
1295           "/x" but NOT "/xx" is turned on for matching "foo".  (One might
1296           mistakenly think that since the inner "(?x)" is already in the
1297           scope of "/x", that the result would effectively be the sum of
1298           them, yielding "/xx".  It doesn't work that way.)  Similarly, doing
1299           something like "(?xx-x)foo" turns off all "x" behavior for matching
1300           "foo", it is not that you subtract 1 "x" from 2 to get 1 "x"
1301           remaining.
1302
1303           Any of these modifiers can be set to apply globally to all regular
1304           expressions compiled within the scope of a "use re".  See "'/flags'
1305           mode" in re.
1306
1307           Starting in Perl 5.14, a "^" (caret or circumflex accent)
1308           immediately after the "?" is a shorthand equivalent to "d-imnsx".
1309           Flags (except "d") may follow the caret to override it.  But a
1310           minus sign is not legal with it.
1311
1312           Note that the "a", "d", "l", "p", and "u" modifiers are special in
1313           that they can only be enabled, not disabled, and the "a", "d", "l",
1314           and "u" modifiers are mutually exclusive: specifying one de-
1315           specifies the others, and a maximum of one (or two "a"'s) may
1316           appear in the construct.  Thus, for example, "(?-p)" will warn when
1317           compiled under "use warnings"; "(?-d:...)" and "(?dl:...)" are
1318           fatal errors.
1319
1320           Note also that the "p" modifier is special in that its presence
1321           anywhere in a pattern has a global effect.
1322
1323       "(?:pattern)"
1324       "(?adluimnsx-imnsx:pattern)"
1325       "(?^aluimnsx:pattern)"
1326           This is for clustering, not capturing; it groups subexpressions
1327           like "()", but doesn't make backreferences as "()" does.  So
1328
1329               @fields = split(/\b(?:a|b|c)\b/)
1330
1331           matches the same field delimiters as
1332
1333               @fields = split(/\b(a|b|c)\b/)
1334
1335           but doesn't spit out the delimiters themselves as extra fields
1336           (even though that's the behaviour of "split" in perlfunc when its
1337           pattern contains capturing groups).  It's also cheaper not to
1338           capture characters if you don't need to.
1339
1340           Any letters between "?" and ":" act as flags modifiers as with
1341           "(?adluimnsx-imnsx)".  For example,
1342
1343               /(?s-i:more.*than).*million/i
1344
1345           is equivalent to the more verbose
1346
1347               /(?:(?s-i)more.*than).*million/i
1348
1349           Note that any "()" constructs enclosed within this one will still
1350           capture unless the "/n" modifier is in effect.
1351
1352           Like the "(?adlupimnsx-imnsx)" construct, "aa" and "a" override
1353           each other, as do "xx" and "x".  They are not additive.  So, doing
1354           something like "(?xx-x:foo)" turns off all "x" behavior for
1355           matching "foo".
1356
1357           Starting in Perl 5.14, a "^" (caret or circumflex accent)
1358           immediately after the "?" is a shorthand equivalent to "d-imnsx".
1359           Any positive flags (except "d") may follow the caret, so
1360
1361               (?^x:foo)
1362
1363           is equivalent to
1364
1365               (?x-imns:foo)
1366
1367           The caret tells Perl that this cluster doesn't inherit the flags of
1368           any surrounding pattern, but uses the system defaults ("d-imnsx"),
1369           modified by any flags specified.
1370
1371           The caret allows for simpler stringification of compiled regular
1372           expressions.  These look like
1373
1374               (?^:pattern)
1375
1376           with any non-default flags appearing between the caret and the
1377           colon.  A test that looks at such stringification thus doesn't need
1378           to have the system default flags hard-coded in it, just the caret.
1379           If new flags are added to Perl, the meaning of the caret's
1380           expansion will change to include the default for those flags, so
1381           the test will still work, unchanged.
1382
1383           Specifying a negative flag after the caret is an error, as the flag
1384           is redundant.
1385
1386           Mnemonic for "(?^...)":  A fresh beginning since the usual use of a
1387           caret is to match at the beginning.
1388
1389       "(?|pattern)"
1390           This is the "branch reset" pattern, which has the special property
1391           that the capture groups are numbered from the same starting point
1392           in each alternation branch. It is available starting from perl
1393           5.10.0.
1394
1395           Capture groups are numbered from left to right, but inside this
1396           construct the numbering is restarted for each branch.
1397
1398           The numbering within each branch will be as normal, and any groups
1399           following this construct will be numbered as though the construct
1400           contained only one branch, that being the one with the most capture
1401           groups in it.
1402
1403           This construct is useful when you want to capture one of a number
1404           of alternative matches.
1405
1406           Consider the following pattern.  The numbers underneath show in
1407           which group the captured content will be stored.
1408
1409               # before  ---------------branch-reset----------- after
1410               / ( a )  (?| x ( y ) z | (p (q) r) | (t) u (v) ) ( z ) /x
1411               # 1            2         2  3        2     3     4
1412
1413           Be careful when using the branch reset pattern in combination with
1414           named captures. Named captures are implemented as being aliases to
1415           numbered groups holding the captures, and that interferes with the
1416           implementation of the branch reset pattern. If you are using named
1417           captures in a branch reset pattern, it's best to use the same
1418           names, in the same order, in each of the alternations:
1419
1420              /(?|  (?<a> x ) (?<b> y )
1421                 |  (?<a> z ) (?<b> w )) /x
1422
1423           Not doing so may lead to surprises:
1424
1425             "12" =~ /(?| (?<a> \d+ ) | (?<b> \D+))/x;
1426             say $+{a};    # Prints '12'
1427             say $+{b};    # *Also* prints '12'.
1428
1429           The problem here is that both the group named "a" and the group
1430           named "b" are aliases for the group belonging to $1.
1431
1432       Lookaround Assertions
1433           Lookaround assertions are zero-width patterns which match a
1434           specific pattern without including it in $&. Positive assertions
1435           match when their subpattern matches, negative assertions match when
1436           their subpattern fails. Lookbehind matches text up to the current
1437           match position, lookahead matches text following the current match
1438           position.
1439
1440           "(?=pattern)"
1441               A zero-width positive lookahead assertion.  For example,
1442               "/\w+(?=\t)/" matches a word followed by a tab, without
1443               including the tab in $&.
1444
1445           "(?!pattern)"
1446               A zero-width negative lookahead assertion.  For example
1447               "/foo(?!bar)/" matches any occurrence of "foo" that isn't
1448               followed by "bar".  Note however that lookahead and lookbehind
1449               are NOT the same thing.  You cannot use this for lookbehind.
1450
1451               If you are looking for a "bar" that isn't preceded by a "foo",
1452               "/(?!foo)bar/" will not do what you want.  That's because the
1453               "(?!foo)" is just saying that the next thing cannot be
1454               "foo"--and it's not, it's a "bar", so "foobar" will match.  Use
1455               lookbehind instead (see below).
1456
1457           "(?<=pattern)"
1458           "\K"
1459               A zero-width positive lookbehind assertion.  For example,
1460               "/(?<=\t)\w+/" matches a word that follows a tab, without
1461               including the tab in $&.  Works only for fixed-width
1462               lookbehind.
1463
1464               There is a special form of this construct, called "\K"
1465               (available since Perl 5.10.0), which causes the regex engine to
1466               "keep" everything it had matched prior to the "\K" and not
1467               include it in $&. This effectively provides variable-length
1468               lookbehind. The use of "\K" inside of another lookaround
1469               assertion is allowed, but the behaviour is currently not well
1470               defined.
1471
1472               For various reasons "\K" may be significantly more efficient
1473               than the equivalent "(?<=...)" construct, and it is especially
1474               useful in situations where you want to efficiently remove
1475               something following something else in a string. For instance
1476
1477                 s/(foo)bar/$1/g;
1478
1479               can be rewritten as the much more efficient
1480
1481                 s/foo\Kbar//g;
1482
1483           "(?<!pattern)"
1484               A zero-width negative lookbehind assertion.  For example
1485               "/(?<!bar)foo/" matches any occurrence of "foo" that does not
1486               follow "bar".  Works only for fixed-width lookbehind.
1487
1488       "(?<NAME>pattern)"
1489       "(?'NAME'pattern)"
1490           A named capture group. Identical in every respect to normal
1491           capturing parentheses "()" but for the additional fact that the
1492           group can be referred to by name in various regular expression
1493           constructs (like "\g{NAME}") and can be accessed by name after a
1494           successful match via "%+" or "%-". See perlvar for more details on
1495           the "%+" and "%-" hashes.
1496
1497           If multiple distinct capture groups have the same name then the
1498           $+{NAME} will refer to the leftmost defined group in the match.
1499
1500           The forms "(?'NAME'pattern)" and "(?<NAME>pattern)" are equivalent.
1501
1502           NOTE: While the notation of this construct is the same as the
1503           similar function in .NET regexes, the behavior is not. In Perl the
1504           groups are numbered sequentially regardless of being named or not.
1505           Thus in the pattern
1506
1507             /(x)(?<foo>y)(z)/
1508
1509           $+{foo} will be the same as $2, and $3 will contain 'z' instead of
1510           the opposite which is what a .NET regex hacker might expect.
1511
1512           Currently NAME is restricted to simple identifiers only.  In other
1513           words, it must match "/^[_A-Za-z][_A-Za-z0-9]*\z/" or its Unicode
1514           extension (see utf8), though it isn't extended by the locale (see
1515           perllocale).
1516
1517           NOTE: In order to make things easier for programmers with
1518           experience with the Python or PCRE regex engines, the pattern
1519           "(?P<NAME>pattern)" may be used instead of "(?<NAME>pattern)";
1520           however this form does not support the use of single quotes as a
1521           delimiter for the name.
1522
1523       "\k<NAME>"
1524       "\k'NAME'"
1525           Named backreference. Similar to numeric backreferences, except that
1526           the group is designated by name and not number. If multiple groups
1527           have the same name then it refers to the leftmost defined group in
1528           the current match.
1529
1530           It is an error to refer to a name not defined by a "(?<NAME>)"
1531           earlier in the pattern.
1532
1533           Both forms are equivalent.
1534
1535           NOTE: In order to make things easier for programmers with
1536           experience with the Python or PCRE regex engines, the pattern
1537           "(?P=NAME)" may be used instead of "\k<NAME>".
1538
1539       "(?{ code })"
1540           WARNING: Using this feature safely requires that you understand its
1541           limitations.  Code executed that has side effects may not perform
1542           identically from version to version due to the effect of future
1543           optimisations in the regex engine.  For more information on this,
1544           see "Embedded Code Execution Frequency".
1545
1546           This zero-width assertion executes any embedded Perl code.  It
1547           always succeeds, and its return value is set as $^R.
1548
1549           In literal patterns, the code is parsed at the same time as the
1550           surrounding code. While within the pattern, control is passed
1551           temporarily back to the perl parser, until the logically-balancing
1552           closing brace is encountered. This is similar to the way that an
1553           array index expression in a literal string is handled, for example
1554
1555               "abc$array[ 1 + f('[') + g()]def"
1556
1557           In particular, braces do not need to be balanced:
1558
1559               s/abc(?{ f('{'); })/def/
1560
1561           Even in a pattern that is interpolated and compiled at run-time,
1562           literal code blocks will be compiled once, at perl compile time;
1563           the following prints "ABCD":
1564
1565               print "D";
1566               my $qr = qr/(?{ BEGIN { print "A" } })/;
1567               my $foo = "foo";
1568               /$foo$qr(?{ BEGIN { print "B" } })/;
1569               BEGIN { print "C" }
1570
1571           In patterns where the text of the code is derived from run-time
1572           information rather than appearing literally in a source code
1573           /pattern/, the code is compiled at the same time that the pattern
1574           is compiled, and for reasons of security, "use re 'eval'" must be
1575           in scope. This is to stop user-supplied patterns containing code
1576           snippets from being executable.
1577
1578           In situations where you need to enable this with "use re 'eval'",
1579           you should also have taint checking enabled.  Better yet, use the
1580           carefully constrained evaluation within a Safe compartment.  See
1581           perlsec for details about both these mechanisms.
1582
1583           From the viewpoint of parsing, lexical variable scope and closures,
1584
1585               /AAA(?{ BBB })CCC/
1586
1587           behaves approximately like
1588
1589               /AAA/ && do { BBB } && /CCC/
1590
1591           Similarly,
1592
1593               qr/AAA(?{ BBB })CCC/
1594
1595           behaves approximately like
1596
1597               sub { /AAA/ && do { BBB } && /CCC/ }
1598
1599           In particular:
1600
1601               { my $i = 1; $r = qr/(?{ print $i })/ }
1602               my $i = 2;
1603               /$r/; # prints "1"
1604
1605           Inside a "(?{...})" block, $_ refers to the string the regular
1606           expression is matching against. You can also use "pos()" to know
1607           what is the current position of matching within this string.
1608
1609           The code block introduces a new scope from the perspective of
1610           lexical variable declarations, but not from the perspective of
1611           "local" and similar localizing behaviours. So later code blocks
1612           within the same pattern will still see the values which were
1613           localized in earlier blocks.  These accumulated localizations are
1614           undone either at the end of a successful match, or if the assertion
1615           is backtracked (compare "Backtracking"). For example,
1616
1617             $_ = 'a' x 8;
1618             m<
1619                (?{ $cnt = 0 })               # Initialize $cnt.
1620                (
1621                  a
1622                  (?{
1623                      local $cnt = $cnt + 1;  # Update $cnt,
1624                                              # backtracking-safe.
1625                  })
1626                )*
1627                aaaa
1628                (?{ $res = $cnt })            # On success copy to
1629                                              # non-localized location.
1630              >x;
1631
1632           will initially increment $cnt up to 8; then during backtracking,
1633           its value will be unwound back to 4, which is the value assigned to
1634           $res.  At the end of the regex execution, $cnt will be wound back
1635           to its initial value of 0.
1636
1637           This assertion may be used as the condition in a
1638
1639               (?(condition)yes-pattern|no-pattern)
1640
1641           switch.  If not used in this way, the result of evaluation of
1642           "code" is put into the special variable $^R.  This happens
1643           immediately, so $^R can be used from other "(?{ code })" assertions
1644           inside the same regular expression.
1645
1646           The assignment to $^R above is properly localized, so the old value
1647           of $^R is restored if the assertion is backtracked; compare
1648           "Backtracking".
1649
1650           Note that the special variable $^N  is particularly useful with
1651           code blocks to capture the results of submatches in variables
1652           without having to keep track of the number of nested parentheses.
1653           For example:
1654
1655             $_ = "The brown fox jumps over the lazy dog";
1656             /the (\S+)(?{ $color = $^N }) (\S+)(?{ $animal = $^N })/i;
1657             print "color = $color, animal = $animal\n";
1658
1659       "(??{ code })"
1660           WARNING: Using this feature safely requires that you understand its
1661           limitations.  Code executed that has side effects may not perform
1662           identically from version to version due to the effect of future
1663           optimisations in the regex engine.  For more information on this,
1664           see "Embedded Code Execution Frequency".
1665
1666           This is a "postponed" regular subexpression.  It behaves in exactly
1667           the same way as a "(?{ code })" code block as described above,
1668           except that its return value, rather than being assigned to $^R, is
1669           treated as a pattern, compiled if it's a string (or used as-is if
1670           its a qr// object), then matched as if it were inserted instead of
1671           this construct.
1672
1673           During the matching of this sub-pattern, it has its own set of
1674           captures which are valid during the sub-match, but are discarded
1675           once control returns to the main pattern. For example, the
1676           following matches, with the inner pattern capturing "B" and
1677           matching "BB", while the outer pattern captures "A";
1678
1679               my $inner = '(.)\1';
1680               "ABBA" =~ /^(.)(??{ $inner })\1/;
1681               print $1; # prints "A";
1682
1683           Note that this means that  there is no way for the inner pattern to
1684           refer to a capture group defined outside.  (The code block itself
1685           can use $1, etc., to refer to the enclosing pattern's capture
1686           groups.)  Thus, although
1687
1688               ('a' x 100)=~/(??{'(.)' x 100})/
1689
1690           will match, it will not set $1 on exit.
1691
1692           The following pattern matches a parenthesized group:
1693
1694            $re = qr{
1695                       \(
1696                       (?:
1697                          (?> [^()]+ )  # Non-parens without backtracking
1698                        |
1699                          (??{ $re })   # Group with matching parens
1700                       )*
1701                       \)
1702                    }x;
1703
1704           See also "(?PARNO)" for a different, more efficient way to
1705           accomplish the same task.
1706
1707           Executing a postponed regular expression too many times without
1708           consuming any input string will also result in a fatal error.  The
1709           depth at which that happens is compiled into perl, so it can be
1710           changed with a custom build.
1711
1712       "(?PARNO)" "(?-PARNO)" "(?+PARNO)" "(?R)" "(?0)"
1713           Recursive subpattern. Treat the contents of a given capture buffer
1714           in the current pattern as an independent subpattern and attempt to
1715           match it at the current position in the string. Information about
1716           capture state from the caller for things like backreferences is
1717           available to the subpattern, but capture buffers set by the
1718           subpattern are not visible to the caller.
1719
1720           Similar to "(??{ code })" except that it does not involve executing
1721           any code or potentially compiling a returned pattern string;
1722           instead it treats the part of the current pattern contained within
1723           a specified capture group as an independent pattern that must match
1724           at the current position. Also different is the treatment of capture
1725           buffers, unlike "(??{ code })" recursive patterns have access to
1726           their caller's match state, so one can use backreferences safely.
1727
1728           PARNO is a sequence of digits (not starting with 0) whose value
1729           reflects the paren-number of the capture group to recurse to.
1730           "(?R)" recurses to the beginning of the whole pattern. "(?0)" is an
1731           alternate syntax for "(?R)". If PARNO is preceded by a plus or
1732           minus sign then it is assumed to be relative, with negative numbers
1733           indicating preceding capture groups and positive ones following.
1734           Thus "(?-1)" refers to the most recently declared group, and
1735           "(?+1)" indicates the next group to be declared.  Note that the
1736           counting for relative recursion differs from that of relative
1737           backreferences, in that with recursion unclosed groups are
1738           included.
1739
1740           The following pattern matches a function "foo()" which may contain
1741           balanced parentheses as the argument.
1742
1743             $re = qr{ (                   # paren group 1 (full function)
1744                         foo
1745                         (                 # paren group 2 (parens)
1746                           \(
1747                             (             # paren group 3 (contents of parens)
1748                             (?:
1749                              (?> [^()]+ ) # Non-parens without backtracking
1750                             |
1751                              (?2)         # Recurse to start of paren group 2
1752                             )*
1753                             )
1754                           \)
1755                         )
1756                       )
1757                     }x;
1758
1759           If the pattern was used as follows
1760
1761               'foo(bar(baz)+baz(bop))'=~/$re/
1762                   and print "\$1 = $1\n",
1763                             "\$2 = $2\n",
1764                             "\$3 = $3\n";
1765
1766           the output produced should be the following:
1767
1768               $1 = foo(bar(baz)+baz(bop))
1769               $2 = (bar(baz)+baz(bop))
1770               $3 = bar(baz)+baz(bop)
1771
1772           If there is no corresponding capture group defined, then it is a
1773           fatal error.  Recursing deeply without consuming any input string
1774           will also result in a fatal error.  The depth at which that happens
1775           is compiled into perl, so it can be changed with a custom build.
1776
1777           The following shows how using negative indexing can make it easier
1778           to embed recursive patterns inside of a "qr//" construct for later
1779           use:
1780
1781               my $parens = qr/(\((?:[^()]++|(?-1))*+\))/;
1782               if (/foo $parens \s+ \+ \s+ bar $parens/x) {
1783                  # do something here...
1784               }
1785
1786           Note that this pattern does not behave the same way as the
1787           equivalent PCRE or Python construct of the same form. In Perl you
1788           can backtrack into a recursed group, in PCRE and Python the
1789           recursed into group is treated as atomic. Also, modifiers are
1790           resolved at compile time, so constructs like "(?i:(?1))" or
1791           "(?:(?i)(?1))" do not affect how the sub-pattern will be processed.
1792
1793       "(?&NAME)"
1794           Recurse to a named subpattern. Identical to "(?PARNO)" except that
1795           the parenthesis to recurse to is determined by name. If multiple
1796           parentheses have the same name, then it recurses to the leftmost.
1797
1798           It is an error to refer to a name that is not declared somewhere in
1799           the pattern.
1800
1801           NOTE: In order to make things easier for programmers with
1802           experience with the Python or PCRE regex engines the pattern
1803           "(?P>NAME)" may be used instead of "(?&NAME)".
1804
1805       "(?(condition)yes-pattern|no-pattern)"
1806       "(?(condition)yes-pattern)"
1807           Conditional expression. Matches "yes-pattern" if "condition" yields
1808           a true value, matches "no-pattern" otherwise. A missing pattern
1809           always matches.
1810
1811           "(condition)" should be one of:
1812
1813           an integer in parentheses
1814               (which is valid if the corresponding pair of parentheses
1815               matched);
1816
1817           a lookahead/lookbehind/evaluate zero-width assertion;
1818           a name in angle brackets or single quotes
1819               (which is valid if a group with the given name matched);
1820
1821           the special symbol "(R)"
1822               (true when evaluated inside of recursion or eval).
1823               Additionally the "R" may be followed by a number, (which will
1824               be true when evaluated when recursing inside of the appropriate
1825               group), or by &NAME, in which case it will be true only when
1826               evaluated during recursion in the named group.
1827
1828           Here's a summary of the possible predicates:
1829
1830           "(1)" "(2)" ...
1831               Checks if the numbered capturing group has matched something.
1832               Full syntax: "(?(1)then|else)"
1833
1834           "(<NAME>)" "('NAME')"
1835               Checks if a group with the given name has matched something.
1836               Full syntax: "(?(<name>)then|else)"
1837
1838           "(?=...)" "(?!...)" "(?<=...)" "(?<!...)"
1839               Checks whether the pattern matches (or does not match, for the
1840               "!"  variants).  Full syntax: "(?(?=lookahead)then|else)"
1841
1842           "(?{ CODE })"
1843               Treats the return value of the code block as the condition.
1844               Full syntax: "(?(?{ code })then|else)"
1845
1846           "(R)"
1847               Checks if the expression has been evaluated inside of
1848               recursion.  Full syntax: "(?(R)then|else)"
1849
1850           "(R1)" "(R2)" ...
1851               Checks if the expression has been evaluated while executing
1852               directly inside of the n-th capture group. This check is the
1853               regex equivalent of
1854
1855                 if ((caller(0))[3] eq 'subname') { ... }
1856
1857               In other words, it does not check the full recursion stack.
1858
1859               Full syntax: "(?(R1)then|else)"
1860
1861           "(R&NAME)"
1862               Similar to "(R1)", this predicate checks to see if we're
1863               executing directly inside of the leftmost group with a given
1864               name (this is the same logic used by "(?&NAME)" to
1865               disambiguate). It does not check the full stack, but only the
1866               name of the innermost active recursion.  Full syntax:
1867               "(?(R&name)then|else)"
1868
1869           "(DEFINE)"
1870               In this case, the yes-pattern is never directly executed, and
1871               no no-pattern is allowed. Similar in spirit to "(?{0})" but
1872               more efficient.  See below for details.  Full syntax:
1873               "(?(DEFINE)definitions...)"
1874
1875           For example:
1876
1877               m{ ( \( )?
1878                  [^()]+
1879                  (?(1) \) )
1880                }x
1881
1882           matches a chunk of non-parentheses, possibly included in
1883           parentheses themselves.
1884
1885           A special form is the "(DEFINE)" predicate, which never executes
1886           its yes-pattern directly, and does not allow a no-pattern. This
1887           allows one to define subpatterns which will be executed only by the
1888           recursion mechanism.  This way, you can define a set of regular
1889           expression rules that can be bundled into any pattern you choose.
1890
1891           It is recommended that for this usage you put the DEFINE block at
1892           the end of the pattern, and that you name any subpatterns defined
1893           within it.
1894
1895           Also, it's worth noting that patterns defined this way probably
1896           will not be as efficient, as the optimizer is not very clever about
1897           handling them.
1898
1899           An example of how this might be used is as follows:
1900
1901             /(?<NAME>(?&NAME_PAT))(?<ADDR>(?&ADDRESS_PAT))
1902              (?(DEFINE)
1903                (?<NAME_PAT>....)
1904                (?<ADDRESS_PAT>....)
1905              )/x
1906
1907           Note that capture groups matched inside of recursion are not
1908           accessible after the recursion returns, so the extra layer of
1909           capturing groups is necessary. Thus $+{NAME_PAT} would not be
1910           defined even though $+{NAME} would be.
1911
1912           Finally, keep in mind that subpatterns created inside a DEFINE
1913           block count towards the absolute and relative number of captures,
1914           so this:
1915
1916               my @captures = "a" =~ /(.)                  # First capture
1917                                      (?(DEFINE)
1918                                          (?<EXAMPLE> 1 )  # Second capture
1919                                      )/x;
1920               say scalar @captures;
1921
1922           Will output 2, not 1. This is particularly important if you intend
1923           to compile the definitions with the "qr//" operator, and later
1924           interpolate them in another pattern.
1925
1926       "(?>pattern)"
1927           An "independent" subexpression, one which matches the substring
1928           that a standalone "pattern" would match if anchored at the given
1929           position, and it matches nothing other than this substring.  This
1930           construct is useful for optimizations of what would otherwise be
1931           "eternal" matches, because it will not backtrack (see
1932           "Backtracking").  It may also be useful in places where the "grab
1933           all you can, and do not give anything back" semantic is desirable.
1934
1935           For example: "^(?>a*)ab" will never match, since "(?>a*)" (anchored
1936           at the beginning of string, as above) will match all characters "a"
1937           at the beginning of string, leaving no "a" for "ab" to match.  In
1938           contrast, "a*ab" will match the same as "a+b", since the match of
1939           the subgroup "a*" is influenced by the following group "ab" (see
1940           "Backtracking").  In particular, "a*" inside "a*ab" will match
1941           fewer characters than a standalone "a*", since this makes the tail
1942           match.
1943
1944           "(?>pattern)" does not disable backtracking altogether once it has
1945           matched. It is still possible to backtrack past the construct, but
1946           not into it. So "((?>a*)|(?>b*))ar" will still match "bar".
1947
1948           An effect similar to "(?>pattern)" may be achieved by writing
1949           "(?=(pattern))\g{-1}".  This matches the same substring as a
1950           standalone "a+", and the following "\g{-1}" eats the matched
1951           string; it therefore makes a zero-length assertion into an analogue
1952           of "(?>...)".  (The difference between these two constructs is that
1953           the second one uses a capturing group, thus shifting ordinals of
1954           backreferences in the rest of a regular expression.)
1955
1956           Consider this pattern:
1957
1958               m{ \(
1959                     (
1960                       [^()]+           # x+
1961                     |
1962                       \( [^()]* \)
1963                     )+
1964                  \)
1965                }x
1966
1967           That will efficiently match a nonempty group with matching
1968           parentheses two levels deep or less.  However, if there is no such
1969           group, it will take virtually forever on a long string.  That's
1970           because there are so many different ways to split a long string
1971           into several substrings.  This is what "(.+)+" is doing, and
1972           "(.+)+" is similar to a subpattern of the above pattern.  Consider
1973           how the pattern above detects no-match on "((()aaaaaaaaaaaaaaaaaa"
1974           in several seconds, but that each extra letter doubles this time.
1975           This exponential performance will make it appear that your program
1976           has hung.  However, a tiny change to this pattern
1977
1978               m{ \(
1979                     (
1980                       (?> [^()]+ )        # change x+ above to (?> x+ )
1981                     |
1982                       \( [^()]* \)
1983                     )+
1984                  \)
1985                }x
1986
1987           which uses "(?>...)" matches exactly when the one above does
1988           (verifying this yourself would be a productive exercise), but
1989           finishes in a fourth the time when used on a similar string with
1990           1000000 "a"s.  Be aware, however, that, when this construct is
1991           followed by a quantifier, it currently triggers a warning message
1992           under the "use warnings" pragma or -w switch saying it "matches
1993           null string many times in regex".
1994
1995           On simple groups, such as the pattern "(?> [^()]+ )", a comparable
1996           effect may be achieved by negative lookahead, as in "[^()]+ (?!
1997           [^()] )".  This was only 4 times slower on a string with 1000000
1998           "a"s.
1999
2000           The "grab all you can, and do not give anything back" semantic is
2001           desirable in many situations where on the first sight a simple
2002           "()*" looks like the correct solution.  Suppose we parse text with
2003           comments being delimited by "#" followed by some optional
2004           (horizontal) whitespace.  Contrary to its appearance, "#[ \t]*" is
2005           not the correct subexpression to match the comment delimiter,
2006           because it may "give up" some whitespace if the remainder of the
2007           pattern can be made to match that way.  The correct answer is
2008           either one of these:
2009
2010               (?>#[ \t]*)
2011               #[ \t]*(?![ \t])
2012
2013           For example, to grab non-empty comments into $1, one should use
2014           either one of these:
2015
2016               / (?> \# [ \t]* ) (        .+ ) /x;
2017               /     \# [ \t]*   ( [^ \t] .* ) /x;
2018
2019           Which one you pick depends on which of these expressions better
2020           reflects the above specification of comments.
2021
2022           In some literature this construct is called "atomic matching" or
2023           "possessive matching".
2024
2025           Possessive quantifiers are equivalent to putting the item they are
2026           applied to inside of one of these constructs. The following
2027           equivalences apply:
2028
2029               Quantifier Form     Bracketing Form
2030               ---------------     ---------------
2031               PAT*+               (?>PAT*)
2032               PAT++               (?>PAT+)
2033               PAT?+               (?>PAT?)
2034               PAT{min,max}+       (?>PAT{min,max})
2035
2036       "(?[ ])"
2037           See "Extended Bracketed Character Classes" in perlrecharclass.
2038
2039           Note that this feature is currently experimental; using it yields a
2040           warning in the "experimental::regex_sets" category.
2041
2042   Backtracking
2043       NOTE: This section presents an abstract approximation of regular
2044       expression behavior.  For a more rigorous (and complicated) view of the
2045       rules involved in selecting a match among possible alternatives, see
2046       "Combining RE Pieces".
2047
2048       A fundamental feature of regular expression matching involves the
2049       notion called backtracking, which is currently used (when needed) by
2050       all regular non-possessive expression quantifiers, namely "*", "*?",
2051       "+", "+?", "{n,m}", and "{n,m}?".  Backtracking is often optimized
2052       internally, but the general principle outlined here is valid.
2053
2054       For a regular expression to match, the entire regular expression must
2055       match, not just part of it.  So if the beginning of a pattern
2056       containing a quantifier succeeds in a way that causes later parts in
2057       the pattern to fail, the matching engine backs up and recalculates the
2058       beginning part--that's why it's called backtracking.
2059
2060       Here is an example of backtracking:  Let's say you want to find the
2061       word following "foo" in the string "Food is on the foo table.":
2062
2063           $_ = "Food is on the foo table.";
2064           if ( /\b(foo)\s+(\w+)/i ) {
2065               print "$2 follows $1.\n";
2066           }
2067
2068       When the match runs, the first part of the regular expression
2069       ("\b(foo)") finds a possible match right at the beginning of the
2070       string, and loads up $1 with "Foo".  However, as soon as the matching
2071       engine sees that there's no whitespace following the "Foo" that it had
2072       saved in $1, it realizes its mistake and starts over again one
2073       character after where it had the tentative match.  This time it goes
2074       all the way until the next occurrence of "foo". The complete regular
2075       expression matches this time, and you get the expected output of "table
2076       follows foo."
2077
2078       Sometimes minimal matching can help a lot.  Imagine you'd like to match
2079       everything between "foo" and "bar".  Initially, you write something
2080       like this:
2081
2082           $_ =  "The food is under the bar in the barn.";
2083           if ( /foo(.*)bar/ ) {
2084               print "got <$1>\n";
2085           }
2086
2087       Which perhaps unexpectedly yields:
2088
2089         got <d is under the bar in the >
2090
2091       That's because ".*" was greedy, so you get everything between the first
2092       "foo" and the last "bar".  Here it's more effective to use minimal
2093       matching to make sure you get the text between a "foo" and the first
2094       "bar" thereafter.
2095
2096           if ( /foo(.*?)bar/ ) { print "got <$1>\n" }
2097         got <d is under the >
2098
2099       Here's another example. Let's say you'd like to match a number at the
2100       end of a string, and you also want to keep the preceding part of the
2101       match.  So you write this:
2102
2103           $_ = "I have 2 numbers: 53147";
2104           if ( /(.*)(\d*)/ ) {                                # Wrong!
2105               print "Beginning is <$1>, number is <$2>.\n";
2106           }
2107
2108       That won't work at all, because ".*" was greedy and gobbled up the
2109       whole string. As "\d*" can match on an empty string the complete
2110       regular expression matched successfully.
2111
2112           Beginning is <I have 2 numbers: 53147>, number is <>.
2113
2114       Here are some variants, most of which don't work:
2115
2116           $_ = "I have 2 numbers: 53147";
2117           @pats = qw{
2118               (.*)(\d*)
2119               (.*)(\d+)
2120               (.*?)(\d*)
2121               (.*?)(\d+)
2122               (.*)(\d+)$
2123               (.*?)(\d+)$
2124               (.*)\b(\d+)$
2125               (.*\D)(\d+)$
2126           };
2127
2128           for $pat (@pats) {
2129               printf "%-12s ", $pat;
2130               if ( /$pat/ ) {
2131                   print "<$1> <$2>\n";
2132               } else {
2133                   print "FAIL\n";
2134               }
2135           }
2136
2137       That will print out:
2138
2139           (.*)(\d*)    <I have 2 numbers: 53147> <>
2140           (.*)(\d+)    <I have 2 numbers: 5314> <7>
2141           (.*?)(\d*)   <> <>
2142           (.*?)(\d+)   <I have > <2>
2143           (.*)(\d+)$   <I have 2 numbers: 5314> <7>
2144           (.*?)(\d+)$  <I have 2 numbers: > <53147>
2145           (.*)\b(\d+)$ <I have 2 numbers: > <53147>
2146           (.*\D)(\d+)$ <I have 2 numbers: > <53147>
2147
2148       As you see, this can be a bit tricky.  It's important to realize that a
2149       regular expression is merely a set of assertions that gives a
2150       definition of success.  There may be 0, 1, or several different ways
2151       that the definition might succeed against a particular string.  And if
2152       there are multiple ways it might succeed, you need to understand
2153       backtracking to know which variety of success you will achieve.
2154
2155       When using lookahead assertions and negations, this can all get even
2156       trickier.  Imagine you'd like to find a sequence of non-digits not
2157       followed by "123".  You might try to write that as
2158
2159           $_ = "ABC123";
2160           if ( /^\D*(?!123)/ ) {                # Wrong!
2161               print "Yup, no 123 in $_\n";
2162           }
2163
2164       But that isn't going to match; at least, not the way you're hoping.  It
2165       claims that there is no 123 in the string.  Here's a clearer picture of
2166       why that pattern matches, contrary to popular expectations:
2167
2168           $x = 'ABC123';
2169           $y = 'ABC445';
2170
2171           print "1: got $1\n" if $x =~ /^(ABC)(?!123)/;
2172           print "2: got $1\n" if $y =~ /^(ABC)(?!123)/;
2173
2174           print "3: got $1\n" if $x =~ /^(\D*)(?!123)/;
2175           print "4: got $1\n" if $y =~ /^(\D*)(?!123)/;
2176
2177       This prints
2178
2179           2: got ABC
2180           3: got AB
2181           4: got ABC
2182
2183       You might have expected test 3 to fail because it seems to a more
2184       general purpose version of test 1.  The important difference between
2185       them is that test 3 contains a quantifier ("\D*") and so can use
2186       backtracking, whereas test 1 will not.  What's happening is that you've
2187       asked "Is it true that at the start of $x, following 0 or more non-
2188       digits, you have something that's not 123?"  If the pattern matcher had
2189       let "\D*" expand to "ABC", this would have caused the whole pattern to
2190       fail.
2191
2192       The search engine will initially match "\D*" with "ABC".  Then it will
2193       try to match "(?!123)" with "123", which fails.  But because a
2194       quantifier ("\D*") has been used in the regular expression, the search
2195       engine can backtrack and retry the match differently in the hope of
2196       matching the complete regular expression.
2197
2198       The pattern really, really wants to succeed, so it uses the standard
2199       pattern back-off-and-retry and lets "\D*" expand to just "AB" this
2200       time.  Now there's indeed something following "AB" that is not "123".
2201       It's "C123", which suffices.
2202
2203       We can deal with this by using both an assertion and a negation.  We'll
2204       say that the first part in $1 must be followed both by a digit and by
2205       something that's not "123".  Remember that the lookaheads are zero-
2206       width expressions--they only look, but don't consume any of the string
2207       in their match.  So rewriting this way produces what you'd expect; that
2208       is, case 5 will fail, but case 6 succeeds:
2209
2210           print "5: got $1\n" if $x =~ /^(\D*)(?=\d)(?!123)/;
2211           print "6: got $1\n" if $y =~ /^(\D*)(?=\d)(?!123)/;
2212
2213           6: got ABC
2214
2215       In other words, the two zero-width assertions next to each other work
2216       as though they're ANDed together, just as you'd use any built-in
2217       assertions:  "/^$/" matches only if you're at the beginning of the line
2218       AND the end of the line simultaneously.  The deeper underlying truth is
2219       that juxtaposition in regular expressions always means AND, except when
2220       you write an explicit OR using the vertical bar.  "/ab/" means match
2221       "a" AND (then) match "b", although the attempted matches are made at
2222       different positions because "a" is not a zero-width assertion, but a
2223       one-width assertion.
2224
2225       WARNING: Particularly complicated regular expressions can take
2226       exponential time to solve because of the immense number of possible
2227       ways they can use backtracking to try for a match.  For example,
2228       without internal optimizations done by the regular expression engine,
2229       this will take a painfully long time to run:
2230
2231           'aaaaaaaaaaaa' =~ /((a{0,5}){0,5})*[c]/
2232
2233       And if you used "*"'s in the internal groups instead of limiting them
2234       to 0 through 5 matches, then it would take forever--or until you ran
2235       out of stack space.  Moreover, these internal optimizations are not
2236       always applicable.  For example, if you put "{0,5}" instead of "*" on
2237       the external group, no current optimization is applicable, and the
2238       match takes a long time to finish.
2239
2240       A powerful tool for optimizing such beasts is what is known as an
2241       "independent group", which does not backtrack (see ""(?>pattern)"").
2242       Note also that zero-length lookahead/lookbehind assertions will not
2243       backtrack to make the tail match, since they are in "logical" context:
2244       only whether they match is considered relevant.  For an example where
2245       side-effects of lookahead might have influenced the following match,
2246       see ""(?>pattern)"".
2247
2248   Special Backtracking Control Verbs
2249       These special patterns are generally of the form "(*VERB:ARG)". Unless
2250       otherwise stated the ARG argument is optional; in some cases, it is
2251       mandatory.
2252
2253       Any pattern containing a special backtracking verb that allows an
2254       argument has the special behaviour that when executed it sets the
2255       current package's $REGERROR and $REGMARK variables. When doing so the
2256       following rules apply:
2257
2258       On failure, the $REGERROR variable will be set to the ARG value of the
2259       verb pattern, if the verb was involved in the failure of the match. If
2260       the ARG part of the pattern was omitted, then $REGERROR will be set to
2261       the name of the last "(*MARK:NAME)" pattern executed, or to TRUE if
2262       there was none. Also, the $REGMARK variable will be set to FALSE.
2263
2264       On a successful match, the $REGERROR variable will be set to FALSE, and
2265       the $REGMARK variable will be set to the name of the last
2266       "(*MARK:NAME)" pattern executed.  See the explanation for the
2267       "(*MARK:NAME)" verb below for more details.
2268
2269       NOTE: $REGERROR and $REGMARK are not magic variables like $1 and most
2270       other regex-related variables. They are not local to a scope, nor
2271       readonly, but instead are volatile package variables similar to
2272       $AUTOLOAD.  They are set in the package containing the code that
2273       executed the regex (rather than the one that compiled it, where those
2274       differ).  If necessary, you can use "local" to localize changes to
2275       these variables to a specific scope before executing a regex.
2276
2277       If a pattern does not contain a special backtracking verb that allows
2278       an argument, then $REGERROR and $REGMARK are not touched at all.
2279
2280       Verbs
2281          "(*PRUNE)" "(*PRUNE:NAME)"
2282              This zero-width pattern prunes the backtracking tree at the
2283              current point when backtracked into on failure. Consider the
2284              pattern "/A (*PRUNE) B/", where A and B are complex patterns.
2285              Until the "(*PRUNE)" verb is reached, A may backtrack as
2286              necessary to match. Once it is reached, matching continues in B,
2287              which may also backtrack as necessary; however, should B not
2288              match, then no further backtracking will take place, and the
2289              pattern will fail outright at the current starting position.
2290
2291              The following example counts all the possible matching strings
2292              in a pattern (without actually matching any of them).
2293
2294                  'aaab' =~ /a+b?(?{print "$&\n"; $count++})(*FAIL)/;
2295                  print "Count=$count\n";
2296
2297              which produces:
2298
2299                  aaab
2300                  aaa
2301                  aa
2302                  a
2303                  aab
2304                  aa
2305                  a
2306                  ab
2307                  a
2308                  Count=9
2309
2310              If we add a "(*PRUNE)" before the count like the following
2311
2312                  'aaab' =~ /a+b?(*PRUNE)(?{print "$&\n"; $count++})(*FAIL)/;
2313                  print "Count=$count\n";
2314
2315              we prevent backtracking and find the count of the longest
2316              matching string at each matching starting point like so:
2317
2318                  aaab
2319                  aab
2320                  ab
2321                  Count=3
2322
2323              Any number of "(*PRUNE)" assertions may be used in a pattern.
2324
2325              See also "(?>pattern)" and possessive quantifiers for other ways
2326              to control backtracking. In some cases, the use of "(*PRUNE)"
2327              can be replaced with a "(?>pattern)" with no functional
2328              difference; however, "(*PRUNE)" can be used to handle cases that
2329              cannot be expressed using a "(?>pattern)" alone.
2330
2331          "(*SKIP)" "(*SKIP:NAME)"
2332              This zero-width pattern is similar to "(*PRUNE)", except that on
2333              failure it also signifies that whatever text that was matched
2334              leading up to the "(*SKIP)" pattern being executed cannot be
2335              part of any match of this pattern. This effectively means that
2336              the regex engine "skips" forward to this position on failure and
2337              tries to match again, (assuming that there is sufficient room to
2338              match).
2339
2340              The name of the "(*SKIP:NAME)" pattern has special significance.
2341              If a "(*MARK:NAME)" was encountered while matching, then it is
2342              that position which is used as the "skip point". If no "(*MARK)"
2343              of that name was encountered, then the "(*SKIP)" operator has no
2344              effect. When used without a name the "skip point" is where the
2345              match point was when executing the "(*SKIP)" pattern.
2346
2347              Compare the following to the examples in "(*PRUNE)"; note the
2348              string is twice as long:
2349
2350               'aaabaaab' =~ /a+b?(*SKIP)(?{print "$&\n"; $count++})(*FAIL)/;
2351               print "Count=$count\n";
2352
2353              outputs
2354
2355                  aaab
2356                  aaab
2357                  Count=2
2358
2359              Once the 'aaab' at the start of the string has matched, and the
2360              "(*SKIP)" executed, the next starting point will be where the
2361              cursor was when the "(*SKIP)" was executed.
2362
2363          "(*MARK:NAME)" "(*:NAME)"
2364              This zero-width pattern can be used to mark the point reached in
2365              a string when a certain part of the pattern has been
2366              successfully matched. This mark may be given a name. A later
2367              "(*SKIP)" pattern will then skip forward to that point if
2368              backtracked into on failure. Any number of "(*MARK)" patterns
2369              are allowed, and the NAME portion may be duplicated.
2370
2371              In addition to interacting with the "(*SKIP)" pattern,
2372              "(*MARK:NAME)" can be used to "label" a pattern branch, so that
2373              after matching, the program can determine which branches of the
2374              pattern were involved in the match.
2375
2376              When a match is successful, the $REGMARK variable will be set to
2377              the name of the most recently executed "(*MARK:NAME)" that was
2378              involved in the match.
2379
2380              This can be used to determine which branch of a pattern was
2381              matched without using a separate capture group for each branch,
2382              which in turn can result in a performance improvement, as perl
2383              cannot optimize "/(?:(x)|(y)|(z))/" as efficiently as something
2384              like "/(?:x(*MARK:x)|y(*MARK:y)|z(*MARK:z))/".
2385
2386              When a match has failed, and unless another verb has been
2387              involved in failing the match and has provided its own name to
2388              use, the $REGERROR variable will be set to the name of the most
2389              recently executed "(*MARK:NAME)".
2390
2391              See "(*SKIP)" for more details.
2392
2393              As a shortcut "(*MARK:NAME)" can be written "(*:NAME)".
2394
2395          "(*THEN)" "(*THEN:NAME)"
2396              This is similar to the "cut group" operator "::" from Perl 6.
2397              Like "(*PRUNE)", this verb always matches, and when backtracked
2398              into on failure, it causes the regex engine to try the next
2399              alternation in the innermost enclosing group (capturing or
2400              otherwise) that has alternations.  The two branches of a
2401              "(?(condition)yes-pattern|no-pattern)" do not count as an
2402              alternation, as far as "(*THEN)" is concerned.
2403
2404              Its name comes from the observation that this operation combined
2405              with the alternation operator ("|") can be used to create what
2406              is essentially a pattern-based if/then/else block:
2407
2408                ( COND (*THEN) FOO | COND2 (*THEN) BAR | COND3 (*THEN) BAZ )
2409
2410              Note that if this operator is used and NOT inside of an
2411              alternation then it acts exactly like the "(*PRUNE)" operator.
2412
2413                / A (*PRUNE) B /
2414
2415              is the same as
2416
2417                / A (*THEN) B /
2418
2419              but
2420
2421                / ( A (*THEN) B | C ) /
2422
2423              is not the same as
2424
2425                / ( A (*PRUNE) B | C ) /
2426
2427              as after matching the A but failing on the B the "(*THEN)" verb
2428              will backtrack and try C; but the "(*PRUNE)" verb will simply
2429              fail.
2430
2431          "(*COMMIT)" "(*COMMIT:args)"
2432              This is the Perl 6 "commit pattern" "<commit>" or ":::". It's a
2433              zero-width pattern similar to "(*SKIP)", except that when
2434              backtracked into on failure it causes the match to fail
2435              outright. No further attempts to find a valid match by advancing
2436              the start pointer will occur again.  For example,
2437
2438               'aaabaaab' =~ /a+b?(*COMMIT)(?{print "$&\n"; $count++})(*FAIL)/;
2439               print "Count=$count\n";
2440
2441              outputs
2442
2443                  aaab
2444                  Count=1
2445
2446              In other words, once the "(*COMMIT)" has been entered, and if
2447              the pattern does not match, the regex engine will not try any
2448              further matching on the rest of the string.
2449
2450          "(*FAIL)" "(*F)" "(*FAIL:arg)"
2451              This pattern matches nothing and always fails. It can be used to
2452              force the engine to backtrack. It is equivalent to "(?!)", but
2453              easier to read. In fact, "(?!)" gets optimised into "(*FAIL)"
2454              internally. You can provide an argument so that if the match
2455              fails because of this "FAIL" directive the argument can be
2456              obtained from $REGERROR.
2457
2458              It is probably useful only when combined with "(?{})" or
2459              "(??{})".
2460
2461          "(*ACCEPT)" "(*ACCEPT:arg)"
2462              This pattern matches nothing and causes the end of successful
2463              matching at the point at which the "(*ACCEPT)" pattern was
2464              encountered, regardless of whether there is actually more to
2465              match in the string. When inside of a nested pattern, such as
2466              recursion, or in a subpattern dynamically generated via
2467              "(??{})", only the innermost pattern is ended immediately.
2468
2469              If the "(*ACCEPT)" is inside of capturing groups then the groups
2470              are marked as ended at the point at which the "(*ACCEPT)" was
2471              encountered.  For instance:
2472
2473                'AB' =~ /(A (A|B(*ACCEPT)|C) D)(E)/x;
2474
2475              will match, and $1 will be "AB" and $2 will be "B", $3 will not
2476              be set. If another branch in the inner parentheses was matched,
2477              such as in the string 'ACDE', then the "D" and "E" would have to
2478              be matched as well.
2479
2480              You can provide an argument, which will be available in the var
2481              $REGMARK after the match completes.
2482
2483   Warning on "\1" Instead of $1
2484       Some people get too used to writing things like:
2485
2486           $pattern =~ s/(\W)/\\\1/g;
2487
2488       This is grandfathered (for \1 to \9) for the RHS of a substitute to
2489       avoid shocking the sed addicts, but it's a dirty habit to get into.
2490       That's because in PerlThink, the righthand side of an "s///" is a
2491       double-quoted string.  "\1" in the usual double-quoted string means a
2492       control-A.  The customary Unix meaning of "\1" is kludged in for
2493       "s///".  However, if you get into the habit of doing that, you get
2494       yourself into trouble if you then add an "/e" modifier.
2495
2496           s/(\d+)/ \1 + 1 /eg;            # causes warning under -w
2497
2498       Or if you try to do
2499
2500           s/(\d+)/\1000/;
2501
2502       You can't disambiguate that by saying "\{1}000", whereas you can fix it
2503       with "${1}000".  The operation of interpolation should not be confused
2504       with the operation of matching a backreference.  Certainly they mean
2505       two different things on the left side of the "s///".
2506
2507   Repeated Patterns Matching a Zero-length Substring
2508       WARNING: Difficult material (and prose) ahead.  This section needs a
2509       rewrite.
2510
2511       Regular expressions provide a terse and powerful programming language.
2512       As with most other power tools, power comes together with the ability
2513       to wreak havoc.
2514
2515       A common abuse of this power stems from the ability to make infinite
2516       loops using regular expressions, with something as innocuous as:
2517
2518           'foo' =~ m{ ( o? )* }x;
2519
2520       The "o?" matches at the beginning of ""foo"", and since the position in
2521       the string is not moved by the match, "o?" would match again and again
2522       because of the "*" quantifier.  Another common way to create a similar
2523       cycle is with the looping modifier "/g":
2524
2525           @matches = ( 'foo' =~ m{ o? }xg );
2526
2527       or
2528
2529           print "match: <$&>\n" while 'foo' =~ m{ o? }xg;
2530
2531       or the loop implied by "split()".
2532
2533       However, long experience has shown that many programming tasks may be
2534       significantly simplified by using repeated subexpressions that may
2535       match zero-length substrings.  Here's a simple example being:
2536
2537           @chars = split //, $string;           # // is not magic in split
2538           ($whitewashed = $string) =~ s/()/ /g; # parens avoid magic s// /
2539
2540       Thus Perl allows such constructs, by forcefully breaking the infinite
2541       loop.  The rules for this are different for lower-level loops given by
2542       the greedy quantifiers "*+{}", and for higher-level ones like the "/g"
2543       modifier or "split()" operator.
2544
2545       The lower-level loops are interrupted (that is, the loop is broken)
2546       when Perl detects that a repeated expression matched a zero-length
2547       substring.   Thus
2548
2549          m{ (?: NON_ZERO_LENGTH | ZERO_LENGTH )* }x;
2550
2551       is made equivalent to
2552
2553          m{ (?: NON_ZERO_LENGTH )* (?: ZERO_LENGTH )? }x;
2554
2555       For example, this program
2556
2557          #!perl -l
2558          "aaaaab" =~ /
2559            (?:
2560               a                 # non-zero
2561               |                 # or
2562              (?{print "hello"}) # print hello whenever this
2563                                 #    branch is tried
2564              (?=(b))            # zero-width assertion
2565            )*  # any number of times
2566           /x;
2567          print $&;
2568          print $1;
2569
2570       prints
2571
2572          hello
2573          aaaaa
2574          b
2575
2576       Notice that "hello" is only printed once, as when Perl sees that the
2577       sixth iteration of the outermost "(?:)*" matches a zero-length string,
2578       it stops the "*".
2579
2580       The higher-level loops preserve an additional state between iterations:
2581       whether the last match was zero-length.  To break the loop, the
2582       following match after a zero-length match is prohibited to have a
2583       length of zero.  This prohibition interacts with backtracking (see
2584       "Backtracking"), and so the second best match is chosen if the best
2585       match is of zero length.
2586
2587       For example:
2588
2589           $_ = 'bar';
2590           s/\w??/<$&>/g;
2591
2592       results in "<><b><><a><><r><>".  At each position of the string the
2593       best match given by non-greedy "??" is the zero-length match, and the
2594       second best match is what is matched by "\w".  Thus zero-length matches
2595       alternate with one-character-long matches.
2596
2597       Similarly, for repeated "m/()/g" the second-best match is the match at
2598       the position one notch further in the string.
2599
2600       The additional state of being matched with zero-length is associated
2601       with the matched string, and is reset by each assignment to "pos()".
2602       Zero-length matches at the end of the previous match are ignored during
2603       "split".
2604
2605   Combining RE Pieces
2606       Each of the elementary pieces of regular expressions which were
2607       described before (such as "ab" or "\Z") could match at most one
2608       substring at the given position of the input string.  However, in a
2609       typical regular expression these elementary pieces are combined into
2610       more complicated patterns using combining operators "ST", "S|T", "S*"
2611       etc.  (in these examples "S" and "T" are regular subexpressions).
2612
2613       Such combinations can include alternatives, leading to a problem of
2614       choice: if we match a regular expression "a|ab" against "abc", will it
2615       match substring "a" or "ab"?  One way to describe which substring is
2616       actually matched is the concept of backtracking (see "Backtracking").
2617       However, this description is too low-level and makes you think in terms
2618       of a particular implementation.
2619
2620       Another description starts with notions of "better"/"worse".  All the
2621       substrings which may be matched by the given regular expression can be
2622       sorted from the "best" match to the "worst" match, and it is the "best"
2623       match which is chosen.  This substitutes the question of "what is
2624       chosen?"  by the question of "which matches are better, and which are
2625       worse?".
2626
2627       Again, for elementary pieces there is no such question, since at most
2628       one match at a given position is possible.  This section describes the
2629       notion of better/worse for combining operators.  In the description
2630       below "S" and "T" are regular subexpressions.
2631
2632       "ST"
2633           Consider two possible matches, "AB" and "A'B'", "A" and "A'" are
2634           substrings which can be matched by "S", "B" and "B'" are substrings
2635           which can be matched by "T".
2636
2637           If "A" is a better match for "S" than "A'", "AB" is a better match
2638           than "A'B'".
2639
2640           If "A" and "A'" coincide: "AB" is a better match than "AB'" if "B"
2641           is a better match for "T" than "B'".
2642
2643       "S|T"
2644           When "S" can match, it is a better match than when only "T" can
2645           match.
2646
2647           Ordering of two matches for "S" is the same as for "S".  Similar
2648           for two matches for "T".
2649
2650       "S{REPEAT_COUNT}"
2651           Matches as "SSS...S" (repeated as many times as necessary).
2652
2653       "S{min,max}"
2654           Matches as "S{max}|S{max-1}|...|S{min+1}|S{min}".
2655
2656       "S{min,max}?"
2657           Matches as "S{min}|S{min+1}|...|S{max-1}|S{max}".
2658
2659       "S?", "S*", "S+"
2660           Same as "S{0,1}", "S{0,BIG_NUMBER}", "S{1,BIG_NUMBER}"
2661           respectively.
2662
2663       "S??", "S*?", "S+?"
2664           Same as "S{0,1}?", "S{0,BIG_NUMBER}?", "S{1,BIG_NUMBER}?"
2665           respectively.
2666
2667       "(?>S)"
2668           Matches the best match for "S" and only that.
2669
2670       "(?=S)", "(?<=S)"
2671           Only the best match for "S" is considered.  (This is important only
2672           if "S" has capturing parentheses, and backreferences are used
2673           somewhere else in the whole regular expression.)
2674
2675       "(?!S)", "(?<!S)"
2676           For this grouping operator there is no need to describe the
2677           ordering, since only whether or not "S" can match is important.
2678
2679       "(??{ EXPR })", "(?PARNO)"
2680           The ordering is the same as for the regular expression which is the
2681           result of EXPR, or the pattern contained by capture group PARNO.
2682
2683       "(?(condition)yes-pattern|no-pattern)"
2684           Recall that which of "yes-pattern" or "no-pattern" actually matches
2685           is already determined.  The ordering of the matches is the same as
2686           for the chosen subexpression.
2687
2688       The above recipes describe the ordering of matches at a given position.
2689       One more rule is needed to understand how a match is determined for the
2690       whole regular expression: a match at an earlier position is always
2691       better than a match at a later position.
2692
2693   Creating Custom RE Engines
2694       As of Perl 5.10.0, one can create custom regular expression engines.
2695       This is not for the faint of heart, as they have to plug in at the C
2696       level.  See perlreapi for more details.
2697
2698       As an alternative, overloaded constants (see overload) provide a simple
2699       way to extend the functionality of the RE engine, by substituting one
2700       pattern for another.
2701
2702       Suppose that we want to enable a new RE escape-sequence "\Y|" which
2703       matches at a boundary between whitespace characters and non-whitespace
2704       characters.  Note that "(?=\S)(?<!\S)|(?!\S)(?<=\S)" matches exactly at
2705       these positions, so we want to have each "\Y|" in the place of the more
2706       complicated version.  We can create a module "customre" to do this:
2707
2708           package customre;
2709           use overload;
2710
2711           sub import {
2712             shift;
2713             die "No argument to customre::import allowed" if @_;
2714             overload::constant 'qr' => \&convert;
2715           }
2716
2717           sub invalid { die "/$_[0]/: invalid escape '\\$_[1]'"}
2718
2719           # We must also take care of not escaping the legitimate \\Y|
2720           # sequence, hence the presence of '\\' in the conversion rules.
2721           my %rules = ( '\\' => '\\\\',
2722                         'Y|' => qr/(?=\S)(?<!\S)|(?!\S)(?<=\S)/ );
2723           sub convert {
2724             my $re = shift;
2725             $re =~ s{
2726                       \\ ( \\ | Y . )
2727                     }
2728                     { $rules{$1} or invalid($re,$1) }sgex;
2729             return $re;
2730           }
2731
2732       Now "use customre" enables the new escape in constant regular
2733       expressions, i.e., those without any runtime variable interpolations.
2734       As documented in overload, this conversion will work only over literal
2735       parts of regular expressions.  For "\Y|$re\Y|" the variable part of
2736       this regular expression needs to be converted explicitly (but only if
2737       the special meaning of "\Y|" should be enabled inside $re):
2738
2739           use customre;
2740           $re = <>;
2741           chomp $re;
2742           $re = customre::convert $re;
2743           /\Y|$re\Y|/;
2744
2745   Embedded Code Execution Frequency
2746       The exact rules for how often "(??{})" and "(?{})" are executed in a
2747       pattern are unspecified.  In the case of a successful match you can
2748       assume that they DWIM and will be executed in left to right order the
2749       appropriate number of times in the accepting path of the pattern as
2750       would any other meta-pattern.  How non-accepting pathways and match
2751       failures affect the number of times a pattern is executed is
2752       specifically unspecified and may vary depending on what optimizations
2753       can be applied to the pattern and is likely to change from version to
2754       version.
2755
2756       For instance in
2757
2758         "aaabcdeeeee"=~/a(?{print "a"})b(?{print "b"})cde/;
2759
2760       the exact number of times "a" or "b" are printed out is unspecified for
2761       failure, but you may assume they will be printed at least once during a
2762       successful match, additionally you may assume that if "b" is printed,
2763       it will be preceded by at least one "a".
2764
2765       In the case of branching constructs like the following:
2766
2767         /a(b|(?{ print "a" }))c(?{ print "c" })/;
2768
2769       you can assume that the input "ac" will output "ac", and that "abc"
2770       will output only "c".
2771
2772       When embedded code is quantified, successful matches will call the code
2773       once for each matched iteration of the quantifier.  For example:
2774
2775         "good" =~ /g(?:o(?{print "o"}))*d/;
2776
2777       will output "o" twice.
2778
2779   PCRE/Python Support
2780       As of Perl 5.10.0, Perl supports several Python/PCRE-specific
2781       extensions to the regex syntax. While Perl programmers are encouraged
2782       to use the Perl-specific syntax, the following are also accepted:
2783
2784       "(?P<NAME>pattern)"
2785           Define a named capture group. Equivalent to "(?<NAME>pattern)".
2786
2787       "(?P=NAME)"
2788           Backreference to a named capture group. Equivalent to "\g{NAME}".
2789
2790       "(?P>NAME)"
2791           Subroutine call to a named capture group. Equivalent to "(?&NAME)".
2792

BUGS

2794       There are a number of issues with regard to case-insensitive matching
2795       in Unicode rules.  See "i" under "Modifiers" above.
2796
2797       This document varies from difficult to understand to completely and
2798       utterly opaque.  The wandering prose riddled with jargon is hard to
2799       fathom in several places.
2800
2801       This document needs a rewrite that separates the tutorial content from
2802       the reference content.
2803

SEE ALSO

2805       The syntax of patterns used in Perl pattern matching evolved from those
2806       supplied in the Bell Labs Research Unix 8th Edition (Version 8) regex
2807       routines.  (The code is actually derived (distantly) from Henry
2808       Spencer's freely redistributable reimplementation of those V8
2809       routines.)
2810
2811       perlrequick.
2812
2813       perlretut.
2814
2815       "Regexp Quote-Like Operators" in perlop.
2816
2817       "Gory details of parsing quoted constructs" in perlop.
2818
2819       perlfaq6.
2820
2821       "pos" in perlfunc.
2822
2823       perllocale.
2824
2825       perlebcdic.
2826
2827       Mastering Regular Expressions by Jeffrey Friedl, published by O'Reilly
2828       and Associates.
2829
2830
2831
2832perl v5.26.3                      2018-03-23                         PERLRE(1)
Impressum