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

BUGS

3104       There are a number of issues with regard to case-insensitive matching
3105       in Unicode rules.  See "i" under "Modifiers" above.
3106
3107       This document varies from difficult to understand to completely and
3108       utterly opaque.  The wandering prose riddled with jargon is hard to
3109       fathom in several places.
3110
3111       This document needs a rewrite that separates the tutorial content from
3112       the reference content.
3113

SEE ALSO

3115       The syntax of patterns used in Perl pattern matching evolved from those
3116       supplied in the Bell Labs Research Unix 8th Edition (Version 8) regex
3117       routines.  (The code is actually derived (distantly) from Henry
3118       Spencer's freely redistributable reimplementation of those V8
3119       routines.)
3120
3121       perlrequick.
3122
3123       perlretut.
3124
3125       "Regexp Quote-Like Operators" in perlop.
3126
3127       "Gory details of parsing quoted constructs" in perlop.
3128
3129       perlfaq6.
3130
3131       "pos" in perlfunc.
3132
3133       perllocale.
3134
3135       perlebcdic.
3136
3137       Mastering Regular Expressions by Jeffrey Friedl, published by O'Reilly
3138       and Associates.
3139
3140
3141
3142perl v5.36.0                      2022-08-30                         PERLRE(1)
Impressum