{
    "content": [
        {
            "type": "text",
            "text": "# perlre (man)\n\n## NAME\n\nperlre - Perl regular expressions\n\n## DESCRIPTION\n\nThis page describes the syntax of regular expressions in Perl.\n\n## Sections\n\n- **NAME**\n- **DESCRIPTION** (14 subsections)\n- **BUGS**\n- **SEE ALSO**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "perlre",
        "section": "",
        "mode": "man",
        "summary": "perlre - Perl regular expressions",
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 14,
                "subsections": [
                    {
                        "name": "The Basics",
                        "lines": 240
                    },
                    {
                        "name": "Modifiers",
                        "lines": 415
                    },
                    {
                        "name": "Regular Expressions",
                        "lines": 368
                    },
                    {
                        "name": "Quoting metacharacters",
                        "lines": 22
                    },
                    {
                        "name": "Extended Patterns",
                        "lines": 817
                    },
                    {
                        "name": "Backtracking",
                        "lines": 183
                    },
                    {
                        "name": "Script Runs",
                        "lines": 100
                    },
                    {
                        "name": "Special Backtracking Control Verbs",
                        "lines": 205
                    },
                    {
                        "name": "Warning on \"\\1\" Instead of $1",
                        "lines": 20
                    },
                    {
                        "name": "Repeated Patterns Matching a Zero-length Substring",
                        "lines": 87
                    },
                    {
                        "name": "Combining RE Pieces",
                        "lines": 73
                    },
                    {
                        "name": "Creating Custom RE Engines",
                        "lines": 48
                    },
                    {
                        "name": "Embedded Code Execution Frequency",
                        "lines": 28
                    },
                    {
                        "name": "PCRE/Python Support",
                        "lines": 13
                    }
                ]
            },
            {
                "name": "BUGS",
                "lines": 8,
                "subsections": []
            },
            {
                "name": "SEE ALSO",
                "lines": 26,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "perlre - Perl regular expressions\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "This page describes the syntax of regular expressions in Perl.\n\nIf you haven't used regular expressions before, a tutorial introduction is available in\nperlretut.  If you know just a little about them, a quick-start introduction is available in\nperlrequick.\n\nExcept for \"The Basics\" section, this page assumes you are familiar with regular expression\nbasics, like what is a \"pattern\", what does it look like, and how it is basically used.  For\na reference on how they are used, plus various examples of the same, see discussions of\n\"m//\", \"s///\", \"qr//\" and \"??\" in \"Regexp Quote-Like Operators\" in perlop.\n\nNew in v5.22, \"use re 'strict'\" applies stricter rules than otherwise when compiling regular\nexpression patterns.  It can find things that, while legal, may not be what you intended.\n",
                "subsections": [
                    {
                        "name": "The Basics",
                        "content": "Regular expressions are strings with the very particular syntax and meaning described in this\ndocument and auxiliary documents referred to by this one.  The strings are called \"patterns\".\nPatterns are used to determine if some other string, called the \"target\", has (or doesn't\nhave) the characteristics specified by the pattern.  We call this \"matching\" the target\nstring against the pattern.  Usually the match is done by having the target be the first\noperand, and the pattern be the second operand, of one of the two binary operators \"=~\" and\n\"!~\", listed in \"Binding Operators\" in perlop; and the pattern will have been converted from\nan ordinary string by one of the operators in \"Regexp Quote-Like Operators\" in perlop, like\nso:\n\n$foo =~ m/abc/\n\nThis evaluates to true if and only if the string in the variable $foo contains somewhere in\nit, the sequence of characters \"a\", \"b\", then \"c\".  (The \"=~ m\", or match operator, is\ndescribed in \"m/PATTERN/msixpodualngc\" in perlop.)\n\nPatterns that aren't already stored in some variable must be delimitted, at both ends, by\ndelimitter characters.  These are often, as in the example above, forward slashes, and the\ntypical way a pattern is written in documentation is with those slashes.  In most cases, the\ndelimitter is the same character, fore and aft, but there are a few cases where a character\nlooks like it has a mirror-image mate, where the opening version is the beginning delimiter,\nand the closing one is the ending delimiter, like\n\n$foo =~ m<abc>\n\nMost times, the pattern is evaluated in double-quotish context, but it is possible to choose\ndelimiters to force single-quotish, like\n\n$foo =~ m'abc'\n\nIf the pattern contains its delimiter within it, that delimiter must be escaped.  Prefixing\nit with a backslash (e.g., \"/foo\\/bar/\") serves this purpose.\n\nAny single character in a pattern matches that same character in the target string, unless\nthe character is a metacharacter with a special meaning described in this document.  A\nsequence of non-metacharacters matches the same sequence in the target string, as we saw\nabove with \"m/abc/\".\n\nOnly a few characters (all of them being ASCII punctuation characters) are metacharacters.\nThe most commonly used one is a dot \".\", which normally matches almost any character\n(including a dot itself).\n\nYou can cause characters that normally function as metacharacters to be interpreted literally\nby prefixing them with a \"\\\", just like the pattern's delimiter must be escaped if it also\noccurs within the pattern.  Thus, \"\\.\" matches just a literal dot, \".\" instead of its normal\nmeaning.  This means that the backslash is also a metacharacter, so \"\\\\\" matches a single\n\"\\\".  And a sequence that contains an escaped metacharacter matches the same sequence (but\nwithout the escape) in the target string.  So, the pattern \"/blur\\\\fl/\" would match any\ntarget string that contains the sequence \"blur\\fl\".\n\nThe metacharacter \"|\" is used to match one thing or another.  Thus\n\n$foo =~ m/this|that/\n\nis TRUE if and only if $foo contains either the sequence \"this\" or the sequence \"that\".  Like\nall metacharacters, prefixing the \"|\" with a backslash makes it match the plain punctuation\ncharacter; in its case, the VERTICAL LINE.\n\n$foo =~ m/this\\|that/\n\nis TRUE if and only if $foo contains the sequence \"this|that\".\n\nYou aren't limited to just a single \"|\".\n\n$foo =~ m/fee|fie|foe|fum/\n\nis TRUE if and only if $foo contains any of those 4 sequences from the children's story \"Jack\nand the Beanstalk\".\n\nAs you can see, the \"|\" binds less tightly than a sequence of ordinary characters.  We can\noverride this by using the grouping metacharacters, the parentheses \"(\" and \")\".\n\n$foo =~ m/th(is|at) thing/\n\nis TRUE if and only if $foo contains either the sequence \"this thing\" or the sequence\n\"that thing\".  The portions of the string that match the portions of the pattern enclosed in\nparentheses are normally made available separately for use later in the pattern,\nsubstitution, or program.  This is called \"capturing\", and it can get complicated.  See\n\"Capture groups\".\n\nThe first alternative includes everything from the last pattern delimiter (\"(\", \"(?:\"\n(described later), etc. or the beginning of the pattern) up to the first \"|\", and the last\nalternative contains everything from the last \"|\" to the next closing pattern delimiter.\nThat's why it's common practice to include alternatives in parentheses: to minimize confusion\nabout where they start and end.\n\nAlternatives are tried from left to right, so the first alternative found for which the\nentire expression matches, is the one that is chosen. This means that alternatives are not\nnecessarily greedy. For example: when matching \"foo|foot\" against \"barefoot\", only the \"foo\"\npart will match, as that is the first alternative tried, and it successfully matches the\ntarget string. (This might not seem important, but it is important when you are capturing\nmatched text using parentheses.)\n\nBesides taking away the special meaning of a metacharacter, a prefixed backslash changes some\nletter and digit characters away from matching just themselves to instead have special\nmeaning.  These are called \"escape sequences\", and all such are described in perlrebackslash.\nA backslash sequence (of a letter or digit) that doesn't currently have special meaning to\nPerl will raise a warning if warnings are enabled, as those are reserved for potential future\nuse.\n\nOne such sequence is \"\\b\", which matches a boundary of some sort.  \"\\b{wb}\" and a few others\ngive specialized types of boundaries.  (They are all described in detail starting at \"\\b{},\n\\b, \\B{}, \\B\" in perlrebackslash.)  Note that these don't match characters, but the zero-\nwidth spaces between characters.  They are an example of a zero-width assertion.  Consider\nagain,\n\n$foo =~ m/fee|fie|foe|fum/\n\nIt evaluates to TRUE if, besides those 4 words, any of the sequences \"feed\", \"field\",\n\"Defoe\", \"fume\", and many others are in $foo.  By judicious use of \"\\b\" (or better (because\nit is designed to handle natural language) \"\\b{wb}\"), we can make sure that only the Giant's\nwords are matched:\n\n$foo =~ m/\\b(fee|fie|foe|fum)\\b/\n$foo =~ m/\\b{wb}(fee|fie|foe|fum)\\b{wb}/\n\nThe final example shows that the characters \"{\" and \"}\" are metacharacters.\n\nAnother use for escape sequences is to specify characters that cannot (or which you prefer\nnot to) be written literally.  These are described in detail in \"Character Escapes\" in\nperlrebackslash, but the next three paragraphs briefly describe some of them.\n\nVarious control characters can be written in C language style: \"\\n\" matches a newline, \"\\t\" a\ntab, \"\\r\" a carriage return, \"\\f\" a form feed, etc.\n\nMore generally, \"\\nnn\", where nnn is a string of three octal digits, matches the character\nwhose native code point is nnn.  You can easily run into trouble if you don't have exactly\nthree digits.  So always use three, or since Perl 5.14, you can use \"\\o{...}\" to specify any\nnumber of octal digits.\n\nSimilarly, \"\\xnn\", where nn are hexadecimal digits, matches the character whose native\nordinal is nn.  Again, not using exactly two digits is a recipe for disaster, but you can use\n\"\\x{...}\" to specify any number of hex digits.\n\nBesides being a metacharacter, the \".\" is an example of a \"character class\", something that\ncan match any single character of a given set of them.  In its case, the set is just about\nall possible characters.  Perl predefines several character classes besides the \".\"; there is\na separate reference page about just these, perlrecharclass.\n\nYou can define your own custom character classes, by putting into your pattern in the\nappropriate place(s), a list of all the characters you want in the set.  You do this by\nenclosing the list within \"[]\" bracket characters.  These are called \"bracketed character\nclasses\" when we are being precise, but often the word \"bracketed\" is dropped.  (Dropping it\nusually doesn't cause confusion.)  This means that the \"[\" character is another\nmetacharacter.  It doesn't match anything just by itself; it is used only to tell Perl that\nwhat follows it is a bracketed character class.  If you want to match a literal left square\nbracket, you must escape it, like \"\\[\".  The matching \"]\" is also a metacharacter; again it\ndoesn't match anything by itself, but just marks the end of your custom class to Perl.  It is\nan example of a \"sometimes metacharacter\".  It isn't a metacharacter if there is no\ncorresponding \"[\", and matches its literal self:\n\nprint \"]\" =~ /]/;  # prints 1\n\nThe list of characters within the character class gives the set of characters matched by the\nclass.  \"[abc]\" matches a single \"a\" or \"b\" or \"c\".  But if the first character after the \"[\"\nis \"^\", the class instead matches any character not in the list.  Within a list, the \"-\"\ncharacter specifies a range of characters, so that \"a-z\" represents all characters between\n\"a\" and \"z\", inclusive.  If you want either \"-\" or \"]\" itself to be a member of a class, put\nit at the start of the list (possibly after a \"^\"), or escape it with a backslash.  \"-\" is\nalso taken literally when it is at the end of the list, just before the closing \"]\".  (The\nfollowing all specify the same class of three characters: \"[-az]\", \"[az-]\", and \"[a\\-z]\".\nAll are different from \"[a-z]\", which specifies a class containing twenty-six characters,\neven on EBCDIC-based character sets.)\n\nThere is lots more to bracketed character classes; full details are in \"Bracketed Character\nClasses\" in perlrecharclass.\n\nMetacharacters\n\n\"The Basics\" introduced some of the metacharacters.  This section gives them all.  Most of\nthem have the same meaning as in the egrep command.\n\nOnly the \"\\\" is always a metacharacter.  The others are metacharacters just sometimes.  The\nfollowing tables lists all of them, summarizes their use, and gives the contexts where they\nare metacharacters.  Outside those contexts or if prefixed by a \"\\\", they match their\ncorresponding punctuation character.  In some cases, their meaning varies depending on\nvarious pattern modifiers that alter the default behaviors.  See \"Modifiers\".\n\nPURPOSE                                  WHERE\n\\   Escape the next character                    Always, except when\nescaped by another \\\n^   Match the beginning of the string            Not in []\n(or line, if /m is used)\n^   Complement the [] class                      At the beginning of []\n.   Match any single character except newline    Not in []\n(under /s, includes newline)\n$   Match the end of the string                  Not in [], but can\n(or before newline at the end of the       mean interpolate a\nstring; or before any newline if /m is     scalar\nused)\n|   Alternation                                  Not in []\n()  Grouping                                     Not in []\n[   Start Bracketed Character class              Not in []\n]   End Bracketed Character class                Only in [], and\nnot first\n*   Matches the preceding element 0 or more      Not in []\ntimes\n+   Matches the preceding element 1 or more      Not in []\ntimes\n?   Matches the preceding element 0 or 1         Not in []\ntimes\n{   Starts a sequence that gives number(s)       Not in []\nof times the preceding element can be\nmatched\n{   when following certain escape sequences\nstarts a modifier to the meaning of the\nsequence\n}   End sequence started by {\n-   Indicates a range                            Only in [] interior\n#   Beginning of comment, extends to line end    Only with /x modifier\n\nNotice that most of the metacharacters lose their special meaning when they occur in a\nbracketed character class, except \"^\" has a different meaning when it is at the beginning of\nsuch a class.  And \"-\" and \"]\" are metacharacters only at restricted positions within\nbracketed character classes; while \"}\" is a metacharacter only when closing a special\nconstruct started by \"{\".\n\nIn double-quotish context, as is usually the case,  you need to be careful about \"$\" and the\nnon-metacharacter \"@\".  Those could interpolate variables, which may or may not be what you\nintended.\n\nThese rules were designed for compactness of expression, rather than legibility and\nmaintainability.  The \"/x and /xx\" pattern modifiers allow you to insert white space to\nimprove readability.  And use of \"re 'strict'\" adds extra checking to catch some typos that\nmight silently compile into something unintended.\n\nBy default, the \"^\" character is guaranteed to match only the beginning of the string, the\n\"$\" character only the end (or before the newline at the end), and Perl does certain\noptimizations with the assumption that the string contains only one line.  Embedded newlines\nwill not be matched by \"^\" or \"$\".  You may, however, wish to treat a string as a multi-line\nbuffer, such that the \"^\" will match after any newline within the string (except if the\nnewline is the last character in the string), and \"$\" will match before any newline.  At the\ncost of a little more overhead, you can do this by using the \"/m\" modifier on the pattern\nmatch operator.  (Older programs did this by setting $*, but this option was removed in perl\n5.10.)\n\nTo simplify multi-line substitutions, the \".\" character never matches a newline unless you\nuse the \"/s\" modifier, which in effect tells Perl to pretend the string is a single\nline--even if it isn't.\n"
                    },
                    {
                        "name": "Modifiers",
                        "content": "Overview\n\nThe default behavior for matching can be changed, using various modifiers.  Modifiers that\nrelate to the interpretation of the pattern are listed just below.  Modifiers that alter the\nway a pattern is used by Perl are detailed in \"Regexp Quote-Like Operators\" in perlop and\n\"Gory details of parsing quoted constructs\" in perlop.  Modifiers can be added dynamically;\nsee \"Extended Patterns\" below.\n\n\"m\" Treat the string being matched against as multiple lines.  That is, change \"^\" and \"$\"\nfrom matching the start of the string's first line and the end of its last line to\nmatching the start and end of each line within the string.\n\n\"s\" Treat the string as single line.  That is, change \".\" to match any character whatsoever,\neven a newline, which normally it would not match.\n\nUsed together, as \"/ms\", they let the \".\" match any character whatsoever, while still\nallowing \"^\" and \"$\" to match, respectively, just after and just before newlines within\nthe string.\n\n\"i\" Do case-insensitive pattern matching.  For example, \"A\" will match \"a\" under \"/i\".\n\nIf locale matching rules are in effect, the case map is taken from the current locale for\ncode points less than 255, and from Unicode rules for larger code points.  However,\nmatches that would cross the Unicode rules/non-Unicode rules boundary (ords 255/256) will\nnot succeed, unless the locale is a UTF-8 one.  See perllocale.\n\nThere are a number of Unicode characters that match a sequence of multiple characters\nunder \"/i\".  For example, \"LATIN SMALL LIGATURE FI\" should match the sequence \"fi\".  Perl\nis not currently able to do this when the multiple characters are in the pattern and are\nsplit between groupings, or when one or more are quantified.  Thus\n\n\"\\N{LATIN SMALL LIGATURE FI}\" =~ /fi/i;          # Matches\n\"\\N{LATIN SMALL LIGATURE FI}\" =~ /[fi][fi]/i;    # Doesn't match!\n\"\\N{LATIN SMALL LIGATURE FI}\" =~ /fi*/i;         # Doesn't match!\n\n# The below doesn't match, and it isn't clear what $1 and $2 would\n# be even if it did!!\n\"\\N{LATIN SMALL LIGATURE FI}\" =~ /(f)(i)/i;      # Doesn't match!\n\nPerl doesn't match multiple characters in a bracketed character class unless the\ncharacter that maps to them is explicitly mentioned, and it doesn't match them at all if\nthe character class is inverted, which otherwise could be highly confusing.  See\n\"Bracketed Character Classes\" in perlrecharclass, and \"Negation\" in perlrecharclass.\n\n\"x\" and \"xx\"\nExtend your pattern's legibility by permitting whitespace and comments.  Details in \"/x\nand  /xx\"\n\n\"p\" Preserve the string matched such that \"${^PREMATCH}\", \"${^MATCH}\", and \"${^POSTMATCH}\"\nare available for use after matching.\n\nIn Perl 5.20 and higher this is ignored. Due to a new copy-on-write mechanism,\n\"${^PREMATCH}\", \"${^MATCH}\", and \"${^POSTMATCH}\" will be available after the match\nregardless of the modifier.\n\n\"a\", \"d\", \"l\", and \"u\"\nThese modifiers, all new in 5.14, affect which character-set rules (Unicode, etc.) are\nused, as described below in \"Character set modifiers\".\n\n\"n\" Prevent the grouping metacharacters \"()\" from capturing. This modifier, new in 5.22, will\nstop $1, $2, etc... from being filled in.\n\n\"hello\" =~ /(hi|hello)/;   # $1 is \"hello\"\n\"hello\" =~ /(hi|hello)/n;  # $1 is undef\n\nThis is equivalent to putting \"?:\" at the beginning of every capturing group:\n\n\"hello\" =~ /(?:hi|hello)/; # $1 is undef\n\n\"/n\" can be negated on a per-group basis. Alternatively, named captures may still be\nused.\n\n\"hello\" =~ /(?-n:(hi|hello))/n;   # $1 is \"hello\"\n\"hello\" =~ /(?<greet>hi|hello)/n; # $1 is \"hello\", $+{greet} is\n# \"hello\"\n\nOther Modifiers\nThere are a number of flags that can be found at the end of regular expression constructs\nthat are not generic regular expression flags, but apply to the operation being\nperformed, like matching or substitution (\"m//\" or \"s///\" respectively).\n\nFlags described further in \"Using regular expressions in Perl\" in perlretut are:\n\nc  - keep the current position during repeated matching\ng  - globally match the pattern repeatedly in the string\n\nSubstitution-specific modifiers described in \"s/PATTERN/REPLACEMENT/msixpodualngcer\" in\nperlop are:\n\ne  - evaluate the right-hand side as an expression\nee - evaluate the right side as a string then eval the result\no  - pretend to optimize your code, but actually introduce bugs\nr  - perform non-destructive substitution and return the new value\n\nRegular expression modifiers are usually written in documentation as e.g., \"the \"/x\"\nmodifier\", even though the delimiter in question might not really be a slash.  The modifiers\n\"/imnsxadlup\" may also be embedded within the regular expression itself using the \"(?...)\"\nconstruct, see \"Extended Patterns\" below.\n\nDetails on some modifiers\n\nSome of the modifiers require more explanation than given in the \"Overview\" above.\n\n\"/x\" and  \"/xx\"\n\nA single \"/x\" tells the regular expression parser to ignore most whitespace that is neither\nbackslashed nor within a bracketed character class.  You can use this to break up your\nregular expression into more readable parts.  Also, the \"#\" character is treated as a\nmetacharacter introducing a comment that runs up to the pattern's closing delimiter, or to\nthe end of the current line if the pattern extends onto the next line.  Hence, this is very\nmuch like an ordinary Perl code comment.  (You can include the closing delimiter within the\ncomment only if you precede it with a backslash, so be careful!)\n\nUse of \"/x\" means that if you want real whitespace or \"#\" characters in the pattern (outside\na bracketed character class, which is unaffected by \"/x\"), then you'll either have to escape\nthem (using backslashes or \"\\Q...\\E\") or encode them using octal, hex, or \"\\N{}\" or\n\"\\p{name=...}\" escapes.  It is ineffective to try to continue a comment onto the next line by\nescaping the \"\\n\" with a backslash or \"\\Q\".\n\nYou can use \"(?#text)\" to create a comment that ends earlier than the end of the current\nline, but \"text\" also can't contain the closing delimiter unless escaped with a backslash.\n\nA common pitfall is to forget that \"#\" characters begin a comment under \"/x\" and are not\nmatched literally.  Just keep that in mind when trying to puzzle out why a particular \"/x\"\npattern isn't working as expected.\n\nStarting in Perl v5.26, if the modifier has a second \"x\" within it, it does everything that a\nsingle \"/x\" does, but additionally non-backslashed SPACE and TAB characters within bracketed\ncharacter classes are also generally ignored, and hence can be added to make the classes more\nreadable.\n\n/ [d-e g-i 3-7]/xx\n/[ ! @ \" # $ % ^ & * () = ? <> ' ]/xx\n\nmay be easier to grasp than the squashed equivalents\n\n/[d-eg-i3-7]/\n/[!@\"#$%^&*()=?<>']/\n\nTaken together, these features go a long way towards making Perl's regular expressions more\nreadable.  Here's an example:\n\n# Delete (most) C comments.\n$program =~ s {\n/\\*     # Match the opening delimiter.\n.*?     # Match a minimal number of characters.\n\\*/     # Match the closing delimiter.\n} []gsx;\n\nNote that anything inside a \"\\Q...\\E\" stays unaffected by \"/x\".  And note that \"/x\" doesn't\naffect space interpretation within a single multi-character construct.  For example \"(?:...)\"\ncan't have a space between the \"(\", \"?\", and \":\".  Within any delimiters for such a\nconstruct, allowed spaces are not affected by \"/x\", and depend on the construct.  For\nexample, all constructs using curly braces as delimiters, such as \"\\x{...}\" can have blanks\nwithin but adjacent to the braces, but not elsewhere, and no non-blank space characters.  An\nexception are Unicode properties which follow Unicode rules, for which see \"Properties\naccessible through \\p{} and \\P{}\" in perluniprops.\n\nThe set of characters that are deemed whitespace are those that Unicode calls \"Pattern White\nSpace\", namely:\n\nU+0009 CHARACTER TABULATION\nU+000A LINE FEED\nU+000B LINE TABULATION\nU+000C FORM FEED\nU+000D CARRIAGE RETURN\nU+0020 SPACE\nU+0085 NEXT LINE\nU+200E LEFT-TO-RIGHT MARK\nU+200F RIGHT-TO-LEFT MARK\nU+2028 LINE SEPARATOR\nU+2029 PARAGRAPH SEPARATOR\n\nCharacter set modifiers\n\n\"/d\", \"/u\", \"/a\", and \"/l\", available starting in 5.14, are called the character set\nmodifiers; they affect the character set rules used for the regular expression.\n\nThe \"/d\", \"/u\", and \"/l\" modifiers are not likely to be of much use to you, and so you need\nnot worry about them very much.  They exist for Perl's internal use, so that complex regular\nexpression data structures can be automatically serialized and later exactly reconstituted,\nincluding all their nuances.  But, since Perl can't keep a secret, and there may be rare\ninstances where they are useful, they are documented here.\n\nThe \"/a\" modifier, on the other hand, may be useful.  Its purpose is to allow code that is to\nwork mostly on ASCII data to not have to concern itself with Unicode.\n\nBriefly, \"/l\" sets the character set to that of whatever Locale is in effect at the time of\nthe execution of the pattern match.\n\n\"/u\" sets the character set to Unicode.\n\n\"/a\" also sets the character set to Unicode, BUT adds several restrictions for ASCII-safe\nmatching.\n\n\"/d\" is the old, problematic, pre-5.14 Default character set behavior.  Its only use is to\nforce that old behavior.\n\nAt any given time, exactly one of these modifiers is in effect.  Their existence allows Perl\nto keep the originally compiled behavior of a regular expression, regardless of what rules\nare in effect when it is actually executed.  And if it is interpolated into a larger regex,\nthe original's rules continue to apply to it, and don't affect the other parts.\n\nThe \"/l\" and \"/u\" modifiers are automatically selected for regular expressions compiled\nwithin the scope of various pragmas, and we recommend that in general, you use those pragmas\ninstead of specifying these modifiers explicitly.  For one thing, the modifiers affect only\npattern matching, and do not extend to even any replacement done, whereas using the pragmas\ngives consistent results for all appropriate operations within their scopes.  For example,\n\ns/foo/\\Ubar/il\n\nwill match \"foo\" using the locale's rules for case-insensitive matching, but the \"/l\" does\nnot affect how the \"\\U\" operates.  Most likely you want both of them to use locale rules.  To\ndo this, instead compile the regular expression within the scope of \"use locale\".  This both\nimplicitly adds the \"/l\", and applies locale rules to the \"\\U\".   The lesson is to \"use\nlocale\", and not \"/l\" explicitly.\n\nSimilarly, it would be better to use \"use feature 'unicodestrings'\" instead of,\n\ns/foo/\\Lbar/iu\n\nto get Unicode rules, as the \"\\L\" in the former (but not necessarily the latter) would also\nuse Unicode rules.\n\nMore detail on each of the modifiers follows.  Most likely you don't need to know this detail\nfor \"/l\", \"/u\", and \"/d\", and can skip ahead to /a.\n\n/l\n\nmeans to use the current locale's rules (see perllocale) when pattern matching.  For example,\n\"\\w\" will match the \"word\" characters of that locale, and \"/i\" case-insensitive matching will\nmatch according to the locale's case folding rules.  The locale used will be the one in\neffect at the time of execution of the pattern match.  This may not be the same as the\ncompilation-time locale, and can differ from one match to another if there is an intervening\ncall of the setlocale() function.\n\nPrior to v5.20, Perl did not support multi-byte locales.  Starting then, UTF-8 locales are\nsupported.  No other multi byte locales are ever likely to be supported.  However, in all\nlocales, one can have code points above 255 and these will always be treated as Unicode no\nmatter what locale is in effect.\n\nUnder Unicode rules, there are a few case-insensitive matches that cross the 255/256\nboundary.  Except for UTF-8 locales in Perls v5.20 and later, these are disallowed under\n\"/l\".  For example, 0xFF (on ASCII platforms) does not caselessly match the character at\n0x178, \"LATIN CAPITAL LETTER Y WITH DIAERESIS\", because 0xFF may not be \"LATIN SMALL LETTER Y\nWITH DIAERESIS\" in the current locale, and Perl has no way of knowing if that character even\nexists in the locale, much less what code point it is.\n\nIn a UTF-8 locale in v5.20 and later, the only visible difference between locale and non-\nlocale in regular expressions should be tainting (see perlsec).\n\nThis modifier may be specified to be the default by \"use locale\", but see \"Which character\nset modifier is in effect?\".\n\n/u\n\nmeans to use Unicode rules when pattern matching.  On ASCII platforms, this means that the\ncode points between 128 and 255 take on their Latin-1 (ISO-8859-1) meanings (which are the\nsame as Unicode's).  (Otherwise Perl considers their meanings to be undefined.)  Thus, under\nthis modifier, the ASCII platform effectively becomes a Unicode platform; and hence, for\nexample, \"\\w\" will match any of the more than 100000 word characters in Unicode.\n\nUnlike most locales, which are specific to a language and country pair, Unicode classifies\nall the characters that are letters somewhere in the world as \"\\w\".  For example, your locale\nmight not think that \"LATIN SMALL LETTER ETH\" is a letter (unless you happen to speak\nIcelandic), but Unicode does.  Similarly, all the characters that are decimal digits\nsomewhere in the world will match \"\\d\"; this is hundreds, not 10, possible matches.  And some\nof those digits look like some of the 10 ASCII digits, but mean a different number, so a\nhuman could easily think a number is a different quantity than it really is.  For example,\n\"BENGALI DIGIT FOUR\" (U+09EA) looks very much like an \"ASCII DIGIT EIGHT\" (U+0038), and\n\"LEPCHA DIGIT SIX\" (U+1C46) looks very much like an \"ASCII DIGIT FIVE\" (U+0035).  And, \"\\d+\",\nmay match strings of digits that are a mixture from different writing systems, creating a\nsecurity issue.  A fraudulent website, for example, could display the price of something\nusing U+1C46, and it would appear to the user that something cost 500 units, but it really\ncosts 600.  A browser that enforced script runs (\"Script Runs\") would prevent that fraudulent\ndisplay.  \"num()\" in Unicode::UCD can also be used to sort this out.  Or the \"/a\" modifier\ncan be used to force \"\\d\" to match just the ASCII 0 through 9.\n\nAlso, under this modifier, case-insensitive matching works on the full set of Unicode\ncharacters.  The \"KELVIN SIGN\", for example matches the letters \"k\" and \"K\"; and \"LATIN SMALL\nLIGATURE FF\" matches the sequence \"ff\", which, if you're not prepared, might make it look\nlike a hexadecimal constant, presenting another potential security issue.  See\n<https://unicode.org/reports/tr36> for a detailed discussion of Unicode security issues.\n\nThis modifier may be specified to be the default by \"use feature 'unicodestrings\", \"use\nlocale ':notcharacters'\", or \"use 5.012\" (or higher), but see \"Which character set modifier\nis in effect?\".\n\n/d\n\nThis modifier means to use the \"Default\" native rules of the platform except when there is\ncause to use Unicode rules instead, as follows:\n\n1.  the target string is encoded in UTF-8; or\n\n2.  the pattern is encoded in UTF-8; or\n\n3.  the pattern explicitly mentions a code point that is above 255 (say by \"\\x{100}\"); or\n\n4.  the pattern uses a Unicode name (\"\\N{...}\");  or\n\n5.  the pattern uses a Unicode property (\"\\p{...}\" or \"\\P{...}\"); or\n\n6.  the pattern uses a Unicode break (\"\\b{...}\" or \"\\B{...}\"); or\n\n7.  the pattern uses \"(?[ ])\"\n\n8.  the pattern uses \"(*scriptrun: ...)\"\n\nAnother mnemonic for this modifier is \"Depends\", as the rules actually used depend on various\nthings, and as a result you can get unexpected results.  See \"The \"Unicode Bug\"\" in\nperlunicode.  The Unicode Bug has become rather infamous, leading to yet other (without\nswearing) names for this modifier, \"Dicey\" and \"Dodgy\".\n\nUnless the pattern or string are encoded in UTF-8, only ASCII characters can match\npositively.\n\nHere are some examples of how that works on an ASCII platform:\n\n$str =  \"\\xDF\";      # $str is not in UTF-8 format.\n$str =~ /^\\w/;       # No match, as $str isn't in UTF-8 format.\n$str .= \"\\x{0e0b}\";  # Now $str is in UTF-8 format.\n$str =~ /^\\w/;       # Match! $str is now in UTF-8 format.\nchop $str;\n$str =~ /^\\w/;       # Still a match! $str remains in UTF-8 format.\n\nThis modifier is automatically selected by default when none of the others are, so yet\nanother name for it is \"Default\".\n\nBecause of the unexpected behaviors associated with this modifier, you probably should only\nexplicitly use it to maintain weird backward compatibilities.\n\n/a (and /aa)\n\nThis modifier stands for ASCII-restrict (or ASCII-safe).  This modifier may be doubled-up to\nincrease its effect.\n\nWhen it appears singly, it causes the sequences \"\\d\", \"\\s\", \"\\w\", and the Posix character\nclasses to match only in the ASCII range.  They thus revert to their pre-5.6, pre-Unicode\nmeanings.  Under \"/a\",  \"\\d\" always means precisely the digits \"0\" to \"9\"; \"\\s\" means the\nfive characters \"[ \\f\\n\\r\\t]\", and starting in Perl v5.18, the vertical tab; \"\\w\" means the\n63 characters \"[A-Za-z0-9]\"; and likewise, all the Posix classes such as \"[[:print:]]\" match\nonly the appropriate ASCII-range characters.\n\nThis modifier is useful for people who only incidentally use Unicode, and who do not wish to\nbe burdened with its complexities and security concerns.\n\nWith \"/a\", one can write \"\\d\" with confidence that it will only match ASCII characters, and\nshould the need arise to match beyond ASCII, you can instead use \"\\p{Digit}\" (or \"\\p{Word}\"\nfor \"\\w\").  There are similar \"\\p{...}\" constructs that can match beyond ASCII both white\nspace (see \"Whitespace\" in perlrecharclass), and Posix classes (see \"POSIX Character Classes\"\nin perlrecharclass).  Thus, this modifier doesn't mean you can't use Unicode, it means that\nto get Unicode matching you must explicitly use a construct (\"\\p{}\", \"\\P{}\") that signals\nUnicode.\n\nAs you would expect, this modifier causes, for example, \"\\D\" to mean the same thing as\n\"[^0-9]\"; in fact, all non-ASCII characters match \"\\D\", \"\\S\", and \"\\W\".  \"\\b\" still means to\nmatch at the boundary between \"\\w\" and \"\\W\", using the \"/a\" definitions of them (similarly\nfor \"\\B\").\n\nOtherwise, \"/a\" behaves like the \"/u\" modifier, in that case-insensitive matching uses\nUnicode rules; for example, \"k\" will match the Unicode \"\\N{KELVIN SIGN}\" under \"/i\" matching,\nand code points in the Latin1 range, above ASCII will have Unicode rules when it comes to\ncase-insensitive matching.\n\nTo forbid ASCII/non-ASCII matches (like \"k\" with \"\\N{KELVIN SIGN}\"), specify the \"a\" twice,\nfor example \"/aai\" or \"/aia\".  (The first occurrence of \"a\" restricts the \"\\d\", etc., and the\nsecond occurrence adds the \"/i\" restrictions.)  But, note that code points outside the ASCII\nrange will use Unicode rules for \"/i\" matching, so the modifier doesn't really restrict\nthings to just ASCII; it just forbids the intermixing of ASCII and non-ASCII.\n\nTo summarize, this modifier provides protection for applications that don't wish to be\nexposed to all of Unicode.  Specifying it twice gives added protection.\n\nThis modifier may be specified to be the default by \"use re '/a'\" or \"use re '/aa'\".  If you\ndo so, you may actually have occasion to use the \"/u\" modifier explicitly if there are a few\nregular expressions where you do want full Unicode rules (but even here, it's best if\neverything were under feature \"unicodestrings\", along with the \"use re '/aa'\").  Also see\n\"Which character set modifier is in effect?\".\n\nWhich character set modifier is in effect?\n\nWhich of these modifiers is in effect at any given point in a regular expression depends on a\nfairly complex set of interactions.  These have been designed so that in general you don't\nhave to worry about it, but this section gives the gory details.  As explained below in\n\"Extended Patterns\" it is possible to explicitly specify modifiers that apply only to\nportions of a regular expression.  The innermost always has priority over any outer ones, and\none applying to the whole expression has priority over any of the default settings that are\ndescribed in the remainder of this section.\n\nThe \"use re '/foo'\" pragma can be used to set default modifiers (including these) for regular\nexpressions compiled within its scope.  This pragma has precedence over the other pragmas\nlisted below that also change the defaults.\n\nOtherwise, \"use locale\" sets the default modifier to \"/l\"; and \"use feature\n'unicodestrings\", or \"use 5.012\" (or higher) set the default to \"/u\" when not in the same\nscope as either \"use locale\" or \"use bytes\".  (\"use locale ':notcharacters'\" also sets the\ndefault to \"/u\", overriding any plain \"use locale\".)  Unlike the mechanisms mentioned above,\nthese affect operations besides regular expressions pattern matching, and so give more\nconsistent results with other operators, including using \"\\U\", \"\\l\", etc. in substitution\nreplacements.\n\nIf none of the above apply, for backwards compatibility reasons, the \"/d\" modifier is the one\nin effect by default.  As this can lead to unexpected results, it is best to specify which\nother rule set should be used.\n\nCharacter set modifier behavior prior to Perl 5.14\n\nPrior to 5.14, there were no explicit modifiers, but \"/l\" was implied for regexes compiled\nwithin the scope of \"use locale\", and \"/d\" was implied otherwise.  However, interpolating a\nregex into a larger regex would ignore the original compilation in favor of whatever was in\neffect at the time of the second compilation.  There were a number of inconsistencies (bugs)\nwith the \"/d\" modifier, where Unicode rules would be used when inappropriate, and vice versa.\n\"\\p{}\" did not imply Unicode rules, and neither did all occurrences of \"\\N{}\", until 5.12.\n"
                    },
                    {
                        "name": "Regular Expressions",
                        "content": "Quantifiers\n\nQuantifiers are used when a particular portion of a pattern needs to match a certain number\n(or numbers) of times.  If there isn't a quantifier the number of times to match is exactly\none.  The following standard quantifiers are recognized:\n\n*           Match 0 or more times\n+           Match 1 or more times\n?           Match 1 or 0 times\n{n}         Match exactly n times\n{n,}        Match at least n times\n{,n}        Match at most n times\n{n,m}       Match at least n but not more than m times\n\n(If a non-escaped curly bracket occurs in a context other than one of the quantifiers listed\nabove, where it does not form part of a backslashed sequence like \"\\x{...}\", it is either a\nfatal syntax error, or treated as a regular character, generally with a deprecation warning\nraised.  To escape it, you can precede it with a backslash (\"\\{\") or enclose it within square\nbrackets  (\"[{]\").  This change will allow for future syntax extensions (like making the\nlower bound of a quantifier optional), and better error checking of quantifiers).\n\nThe \"*\" quantifier is equivalent to \"{0,}\", the \"+\" quantifier to \"{1,}\", and the \"?\"\nquantifier to \"{0,1}\".  n and m are limited to non-negative integral values less than a\npreset limit defined when perl is built.  This is usually 65534 on the most common platforms.\nThe actual limit can be seen in the error message generated by code such as this:\n\n$ = $ , / {$} / for 2 .. 42;\n\nBy default, a quantified subpattern is \"greedy\", that is, it will match as many times as\npossible (given a particular starting location) while still allowing the rest of the pattern\nto match.  If you want it to match the minimum number of times possible, follow the\nquantifier with a \"?\".  Note that the meanings don't change, just the \"greediness\":\n\n*?        Match 0 or more times, not greedily\n+?        Match 1 or more times, not greedily\n??        Match 0 or 1 time, not greedily\n{n}?      Match exactly n times, not greedily (redundant)\n{n,}?     Match at least n times, not greedily\n{,n}?     Match at most n times, not greedily\n{n,m}?    Match at least n but not more than m times, not greedily\n\nNormally when a quantified subpattern does not allow the rest of the overall pattern to\nmatch, Perl will backtrack. However, this behaviour is sometimes undesirable. Thus Perl\nprovides the \"possessive\" quantifier form as well.\n\n*+     Match 0 or more times and give nothing back\n++     Match 1 or more times and give nothing back\n?+     Match 0 or 1 time and give nothing back\n{n}+   Match exactly n times and give nothing back (redundant)\n{n,}+  Match at least n times and give nothing back\n{,n}+  Match at most n times and give nothing back\n{n,m}+ Match at least n but not more than m times and give nothing back\n\nFor instance,\n\n'aaaa' =~ /a++a/\n\nwill never match, as the \"a++\" will gobble up all the \"a\"'s in the string and won't leave any\nfor the remaining part of the pattern. This feature can be extremely useful to give perl\nhints about where it shouldn't backtrack. For instance, the typical \"match a double-quoted\nstring\" problem can be most efficiently performed when written as:\n\n/\"(?:[^\"\\\\]++|\\\\.)*+\"/\n\nas we know that if the final quote does not match, backtracking will not help. See the\nindependent subexpression \"(?>pattern)\" for more details; possessive quantifiers are just\nsyntactic sugar for that construct. For instance the above example could also be written as\nfollows:\n\n/\"(?>(?:(?>[^\"\\\\]+)|\\\\.)*)\"/\n\nNote that the possessive quantifier modifier can not be combined with the non-greedy\nmodifier. This is because it would make no sense.  Consider the follow equivalency table:\n\nIllegal         Legal\n------------    ------\nX??+            X{0}\nX+?+            X{1}\nX{min,max}?+    X{min}\n\nEscape sequences\n\nBecause patterns are processed as double-quoted strings, the following also work:\n\n\\t          tab                   (HT, TAB)\n\\n          newline               (LF, NL)\n\\r          return                (CR)\n\\f          form feed             (FF)\n\\a          alarm (bell)          (BEL)\n\\e          escape (think troff)  (ESC)\n\\cK         control char          (example: VT)\n\\x{}, \\x00  character whose ordinal is the given hexadecimal number\n\\N{name}    named Unicode character or character sequence\n\\N{U+263D}  Unicode character     (example: FIRST QUARTER MOON)\n\\o{}, \\000  character whose ordinal is the given octal number\n\\l          lowercase next char (think vi)\n\\u          uppercase next char (think vi)\n\\L          lowercase until \\E (think vi)\n\\U          uppercase until \\E (think vi)\n\\Q          quote (disable) pattern metacharacters until \\E\n\\E          end either case modification or quoted section, think vi\n\nDetails are in \"Quote and Quote-like Operators\" in perlop.\n\nCharacter Classes and other Special Escapes\n\nIn addition, Perl defines the following:\n\nSequence   Note    Description\n[...]     [1]  Match a character according to the rules of the\nbracketed character class defined by the \"...\".\nExample: [a-z] matches \"a\" or \"b\" or \"c\" ... or \"z\"\n[[:...:]] [2]  Match a character according to the rules of the POSIX\ncharacter class \"...\" within the outer bracketed\ncharacter class.  Example: [[:upper:]] matches any\nuppercase character.\n(?[...])  [8]  Extended bracketed character class\n\\w        [3]  Match a \"word\" character (alphanumeric plus \"\", plus\nother connector punctuation chars plus Unicode\nmarks)\n\\W        [3]  Match a non-\"word\" character\n\\s        [3]  Match a whitespace character\n\\S        [3]  Match a non-whitespace character\n\\d        [3]  Match a decimal digit character\n\\D        [3]  Match a non-digit character\n\\pP       [3]  Match P, named property.  Use \\p{Prop} for longer names\n\\PP       [3]  Match non-P\n\\X        [4]  Match Unicode \"eXtended grapheme cluster\"\n\\1        [5]  Backreference to a specific capture group or buffer.\n'1' may actually be any positive integer.\n\\g1       [5]  Backreference to a specific or previous group,\n\\g{-1}    [5]  The number may be negative indicating a relative\nprevious group and may optionally be wrapped in\ncurly brackets for safer parsing.\n\\g{name}  [5]  Named backreference\n\\k<name>  [5]  Named backreference\n\\k'name'  [5]  Named backreference\n\\k{name}  [5]  Named backreference\n\\K        [6]  Keep the stuff left of the \\K, don't include it in $&\n\\N        [7]  Any character but \\n.  Not affected by /s modifier\n\\v        [3]  Vertical whitespace\n\\V        [3]  Not vertical whitespace\n\\h        [3]  Horizontal whitespace\n\\H        [3]  Not horizontal whitespace\n\\R        [4]  Linebreak\n\n[1] See \"Bracketed Character Classes\" in perlrecharclass for details.\n\n[2] See \"POSIX Character Classes\" in perlrecharclass for details.\n\n[3] See \"Unicode Character Properties\" in perlunicode for details\n\n[4] See \"Misc\" in perlrebackslash for details.\n\n[5] See \"Capture groups\" below for details.\n\n[6] See \"Extended Patterns\" below for details.\n\n[7] Note that \"\\N\" has two meanings.  When of the form \"\\N{NAME}\", it matches the character\nor character sequence whose name is NAME; and similarly when of the form \"\\N{U+hex}\", it\nmatches the character whose Unicode code point is hex.  Otherwise it matches any\ncharacter but \"\\n\".\n\n[8] See \"Extended Bracketed Character Classes\" in perlrecharclass for details.\n\nAssertions\n\nBesides \"^\" and \"$\", Perl defines the following zero-width assertions:\n\n\\b{}   Match at Unicode boundary of specified type\n\\B{}   Match where corresponding \\b{} doesn't match\n\\b     Match a \\w\\W or \\W\\w boundary\n\\B     Match except at a \\w\\W or \\W\\w boundary\n\\A     Match only at beginning of string\n\\Z     Match only at end of string, or before newline at the end\n\\z     Match only at end of string\n\\G     Match only at pos() (e.g. at the end-of-match position\nof prior m//g)\n\nA Unicode boundary (\"\\b{}\"), available starting in v5.22, is a spot between two characters,\nor before the first character in the string, or after the final character in the string where\ncertain criteria defined by Unicode are met.  See \"\\b{}, \\b, \\B{}, \\B\" in perlrebackslash for\ndetails.\n\nA word boundary (\"\\b\") is a spot between two characters that has a \"\\w\" on one side of it and\na \"\\W\" on the other side of it (in either order), counting the imaginary characters off the\nbeginning and end of the string as matching a \"\\W\".  (Within character classes \"\\b\"\nrepresents backspace rather than a word boundary, just as it normally does in any double-\nquoted string.)  The \"\\A\" and \"\\Z\" are just like \"^\" and \"$\", except that they won't match\nmultiple times when the \"/m\" modifier is used, while \"^\" and \"$\" will match at every internal\nline boundary.  To match the actual end of the string and not ignore an optional trailing\nnewline, use \"\\z\".\n\nThe \"\\G\" assertion can be used to chain global matches (using \"m//g\"), as described in\n\"Regexp Quote-Like Operators\" in perlop.  It is also useful when writing \"lex\"-like scanners,\nwhen you have several patterns that you want to match against consequent substrings of your\nstring; see the previous reference.  The actual location where \"\\G\" will match can also be\ninfluenced by using \"pos()\" as an lvalue: see \"pos\" in perlfunc. Note that the rule for zero-\nlength matches (see \"Repeated Patterns Matching a Zero-length Substring\") is modified\nsomewhat, in that contents to the left of \"\\G\" are not counted when determining the length of\nthe match. Thus the following will not match forever:\n\nmy $string = 'ABC';\npos($string) = 1;\nwhile ($string =~ /(.\\G)/g) {\nprint $1;\n}\n\nIt will print 'A' and then terminate, as it considers the match to be zero-width, and thus\nwill not match at the same position twice in a row.\n\nIt is worth noting that \"\\G\" improperly used can result in an infinite loop. Take care when\nusing patterns that include \"\\G\" in an alternation.\n\nNote also that \"s///\" will refuse to overwrite part of a substitution that has already been\nreplaced; so for example this will stop after the first iteration, rather than iterating its\nway backwards through the string:\n\n$ = \"123456789\";\npos = 6;\ns/.(?=.\\G)/X/g;\nprint;      # prints 1234X6789, not XXXXX6789\n\nCapture groups\n\nThe grouping construct \"( ... )\" creates capture groups (also referred to as capture\nbuffers). To refer to the current contents of a group later on, within the same pattern, use\n\"\\g1\" (or \"\\g{1}\") for the first, \"\\g2\" (or \"\\g{2}\") for the second, and so on.  This is\ncalled a backreference.\n\n\n\n\n\n\n\n\nThere is no limit to the number of captured substrings that you may use.  Groups are numbered\nwith the leftmost open parenthesis being number 1, etc.  If a group did not match, the\nassociated backreference won't match either. (This can happen if the group is optional, or in\na different branch of an alternation.)  You can omit the \"g\", and write \"\\1\", etc, but there\nare some issues with this form, described below.\n\nYou can also refer to capture groups relatively, by using a negative number, so that \"\\g-1\"\nand \"\\g{-1}\" both refer to the immediately preceding capture group, and \"\\g-2\" and \"\\g{-2}\"\nboth refer to the group before it.  For example:\n\n/\n(Y)            # group 1\n(              # group 2\n(X)         # group 3\n\\g{-1}      # backref to group 3\n\\g{-3}      # backref to group 1\n)\n/x\n\nwould match the same as \"/(Y) ( (X) \\g3 \\g1 )/x\".  This allows you to interpolate regexes\ninto larger regexes and not have to worry about the capture groups being renumbered.\n\nYou can dispense with numbers altogether and create named capture groups.  The notation is\n\"(?<name>...)\" to declare and \"\\g{name}\" to reference.  (To be compatible with .Net regular\nexpressions, \"\\g{name}\" may also be written as \"\\k{name}\", \"\\k<name>\" or \"\\k'name'\".)  name\nmust not begin with a number, nor contain hyphens.  When different groups within the same\npattern have the same name, any reference to that name assumes the leftmost defined group.\nNamed groups count in absolute and relative numbering, and so can also be referred to by\nthose numbers.  (It's possible to do things with named capture groups that would otherwise\nrequire \"(??{})\".)\n\nCapture group contents are dynamically scoped and available to you outside the pattern until\nthe end of the enclosing block or until the next successful match, whichever comes first.\n(See \"Compound Statements\" in perlsyn.)  You can refer to them by absolute number (using \"$1\"\ninstead of \"\\g1\", etc); or by name via the \"%+\" hash, using \"$+{name}\".\n\nBraces are required in referring to named capture groups, but are optional for absolute or\nrelative numbered ones.  Braces are safer when creating a regex by concatenating smaller\nstrings.  For example if you have \"qr/$a$b/\", and $a contained \"\\g1\", and $b contained \"37\",\nyou would get \"/\\g137/\" which is probably not what you intended.\n\nIf you use braces, you may also optionally add any number of blank (space or tab) characters\nwithin but adjacent to the braces, like \"\\g{ -1 }\", or \"\\k{ name }\".\n\nThe \"\\g\" and \"\\k\" notations were introduced in Perl 5.10.0.  Prior to that there were no\nnamed nor relative numbered capture groups.  Absolute numbered groups were referred to using\n\"\\1\", \"\\2\", etc., and this notation is still accepted (and likely always will be).  But it\nleads to some ambiguities if there are more than 9 capture groups, as \"\\10\" could mean either\nthe tenth capture group, or the character whose ordinal in octal is 010 (a backspace in\nASCII).  Perl resolves this ambiguity by interpreting \"\\10\" as a backreference only if at\nleast 10 left parentheses have opened before it.  Likewise \"\\11\" is a backreference only if\nat least 11 left parentheses have opened before it.  And so on.  \"\\1\" through \"\\9\" are always\ninterpreted as backreferences.  There are several examples below that illustrate these\nperils.  You can avoid the ambiguity by always using \"\\g{}\" or \"\\g\" if you mean capturing\ngroups; and for octal constants always using \"\\o{}\", or for \"\\077\" and below, using 3 digits\npadded with leading zeros, since a leading zero implies an octal constant.\n\nThe \"\\digit\" notation also works in certain circumstances outside the pattern.  See \"Warning\non \\1 Instead of $1\" below for details.\n\nExamples:\n\ns/^([^ ]*) *([^ ]*)/$2 $1/;     # swap first two words\n\n/(.)\\g1/                        # find first doubled char\nand print \"'$1' is the first doubled character\\n\";\n\n/(?<char>.)\\k<char>/            # ... a different way\nand print \"'$+{char}' is the first doubled character\\n\";\n\n/(?'char'.)\\g1/                 # ... mix and match\nand print \"'$1' is the first doubled character\\n\";\n\nif (/Time: (..):(..):(..)/) {   # parse out values\n$hours = $1;\n$minutes = $2;\n$seconds = $3;\n}\n\n/(.)(.)(.)(.)(.)(.)(.)(.)(.)\\g10/   # \\g10 is a backreference\n/(.)(.)(.)(.)(.)(.)(.)(.)(.)\\10/    # \\10 is octal\n/((.)(.)(.)(.)(.)(.)(.)(.)(.))\\10/  # \\10 is a backreference\n/((.)(.)(.)(.)(.)(.)(.)(.)(.))\\010/ # \\010 is octal\n\n$a = '(.)\\1';        # Creates problems when concatenated.\n$b = '(.)\\g{1}';     # Avoids the problems.\n\"aa\" =~ /${a}/;      # True\n\"aa\" =~ /${b}/;      # True\n\"aa0\" =~ /${a}0/;    # False!\n\"aa0\" =~ /${b}0/;    # True\n\"aa\\x08\" =~ /${a}0/;  # True!\n\"aa\\x08\" =~ /${b}0/;  # False\n\nSeveral special variables also refer back to portions of the previous match.  $+ returns\nwhatever the last bracket match matched.  $& returns the entire matched string.  (At one\npoint $0 did also, but now it returns the name of the program.)  \"$`\" returns everything\nbefore the matched string.  \"$'\" returns everything after the matched string. And $^N\ncontains whatever was matched by the most-recently closed group (submatch). $^N can be used\nin extended patterns (see below), for example to assign a submatch to a variable.\n\nThese special variables, like the \"%+\" hash and the numbered match variables ($1, $2, $3,\netc.) are dynamically scoped until the end of the enclosing block or until the next\nsuccessful match, whichever comes first.  (See \"Compound Statements\" in perlsyn.)\n\nNOTE: Failed matches in Perl do not reset the match variables, which makes it easier to write\ncode that tests for a series of more specific cases and remembers the best match.\n\nWARNING: If your code is to run on Perl 5.16 or earlier, beware that once Perl sees that you\nneed one of $&, \"$`\", or \"$'\" anywhere in the program, it has to provide them for every\npattern match.  This may substantially slow your program.\n\nPerl uses the same mechanism to produce $1, $2, etc, so you also pay a price for each pattern\nthat contains capturing parentheses.  (To avoid this cost while retaining the grouping\nbehaviour, use the extended regular expression \"(?: ... )\" instead.)  But if you never use\n$&, \"$`\" or \"$'\", then patterns without capturing parentheses will not be penalized.  So\navoid $&, \"$'\", and \"$`\" if you can, but if you can't (and some algorithms really appreciate\nthem), once you've used them once, use them at will, because you've already paid the price.\n\nPerl 5.16 introduced a slightly more efficient mechanism that notes separately whether each\nof \"$`\", $&, and \"$'\" have been seen, and thus may only need to copy part of the string.\nPerl 5.20 introduced a much more efficient copy-on-write mechanism which eliminates any\nslowdown.\n\nAs another workaround for this problem, Perl 5.10.0 introduced \"${^PREMATCH}\", \"${^MATCH}\"\nand \"${^POSTMATCH}\", which are equivalent to \"$`\", $& and \"$'\", except that they are only\nguaranteed to be defined after a successful match that was executed with the \"/p\" (preserve)\nmodifier.  The use of these variables incurs no global performance penalty, unlike their\npunctuation character equivalents, however at the trade-off that you have to tell perl when\nyou want to use them.  As of Perl 5.20, these three variables are equivalent to \"$`\", $& and\n\"$'\", and \"/p\" is ignored.\n"
                    },
                    {
                        "name": "Quoting metacharacters",
                        "content": "Backslashed metacharacters in Perl are alphanumeric, such as \"\\b\", \"\\w\", \"\\n\".  Unlike some\nother regular expression languages, there are no backslashed symbols that aren't\nalphanumeric.  So anything that looks like \"\\\\\", \"\\(\", \"\\)\", \"\\[\", \"\\]\", \"\\{\", or \"\\}\" is\nalways interpreted as a literal character, not a metacharacter.  This was once used in a\ncommon idiom to disable or quote the special meanings of regular expression metacharacters in\na string that you want to use for a pattern. Simply quote all non-\"word\" characters:\n\n$pattern =~ s/(\\W)/\\\\$1/g;\n\n(If \"use locale\" is set, then this depends on the current locale.)  Today it is more common\nto use the \"quotemeta()\" function or the \"\\Q\" metaquoting escape sequence to disable all\nmetacharacters' special meanings like this:\n\n/$unquoted\\Q$quoted\\E$unquoted/\n\nBeware that if you put literal backslashes (those not inside interpolated variables) between\n\"\\Q\" and \"\\E\", double-quotish backslash interpolation may lead to confusing results.  If you\nneed to use literal backslashes within \"\\Q...\\E\", consult \"Gory details of parsing quoted\nconstructs\" in perlop.\n\n\"quotemeta()\" and \"\\Q\" are fully described in \"quotemeta\" in perlfunc.\n"
                    },
                    {
                        "name": "Extended Patterns",
                        "content": "Perl also defines a consistent extension syntax for features not found in standard tools like\nawk and lex.  The syntax for most of these is a pair of parentheses with a question mark as\nthe first thing within the parentheses.  The character after the question mark indicates the\nextension.\n\nA question mark was chosen for this and for the minimal-matching construct because 1)\nquestion marks are rare in older regular expressions, and 2) whenever you see one, you should\nstop and \"question\" exactly what is going on.  That's psychology....\n\n\"(?#text)\"\nA comment.  The text is ignored.  Note that Perl closes the comment as soon as it sees a\n\")\", so there is no way to put a literal \")\" in the comment.  The pattern's closing\ndelimiter must be escaped by a backslash if it appears in the comment.\n\nSee \"/x\" for another way to have comments in patterns.\n\nNote that a comment can go just about anywhere, except in the middle of an escape\nsequence.   Examples:\n\nqr/foo(?#comment)bar/'  # Matches 'foobar'\n\n# The pattern below matches 'abcd', 'abccd', or 'abcccd'\nqr/abc(?#comment between literal and its quantifier){1,3}d/\n\n# The pattern below generates a syntax error, because the '\\p' must\n# be followed immediately by a '{'.\nqr/\\p(?#comment between \\p and its property name){Any}/\n\n# The pattern below generates a syntax error, because the initial\n# '\\(' is a literal opening parenthesis, and so there is nothing\n# for the  closing ')' to match\nqr/\\(?#the backslash means this isn't a comment)p{Any}/\n\n# Comments can be used to fold long patterns into multiple lines\nqr/First part of a long regex(?#\n)remaining part/\n\n\"(?adlupimnsx-imnsx)\"\n\"(?^alupimnsx)\"\nZero or more embedded pattern-match modifiers, to be turned on (or turned off if preceded\nby \"-\") for the remainder of the pattern or the remainder of the enclosing pattern group\n(if any).\n\nThis is particularly useful for dynamically-generated patterns, such as those read in\nfrom a configuration file, taken from an argument, or specified in a table somewhere.\nConsider the case where some patterns want to be case-sensitive and some do not:  The\ncase-insensitive ones merely need to include \"(?i)\" at the front of the pattern.  For\nexample:\n\n$pattern = \"foobar\";\nif ( /$pattern/i ) { }\n\n# more flexible:\n\n$pattern = \"(?i)foobar\";\nif ( /$pattern/ ) { }\n\nThese modifiers are restored at the end of the enclosing group. For example,\n\n( (?i) blah ) \\s+ \\g1\n\nwill match \"blah\" in any case, some spaces, and an exact (including the case!)\nrepetition of the previous word, assuming the \"/x\" modifier, and no \"/i\" modifier outside\nthis group.\n\nThese modifiers do not carry over into named subpatterns called in the enclosing group.\nIn other words, a pattern such as \"((?i)(?&NAME))\" does not change the case-sensitivity\nof the NAME pattern.\n\nA modifier is overridden by later occurrences of this construct in the same scope\ncontaining the same modifier, so that\n\n/((?im)foo(?-m)bar)/\n\nmatches all of \"foobar\" case insensitively, but uses \"/m\" rules for only the \"foo\"\nportion.  The \"a\" flag overrides \"aa\" as well; likewise \"aa\" overrides \"a\".  The same\ngoes for \"x\" and \"xx\".  Hence, in\n\n/(?-x)foo/xx\n\nboth \"/x\" and \"/xx\" are turned off during matching \"foo\".  And in\n\n/(?x)foo/x\n\n\"/x\" but NOT \"/xx\" is turned on for matching \"foo\".  (One might mistakenly think that\nsince the inner \"(?x)\" is already in the scope of \"/x\", that the result would effectively\nbe the sum of them, yielding \"/xx\".  It doesn't work that way.)  Similarly, doing\nsomething like \"(?xx-x)foo\" turns off all \"x\" behavior for matching \"foo\", it is not that\nyou subtract 1 \"x\" from 2 to get 1 \"x\" remaining.\n\nAny of these modifiers can be set to apply globally to all regular expressions compiled\nwithin the scope of a \"use re\".  See \"'/flags' mode\" in re.\n\nStarting in Perl 5.14, a \"^\" (caret or circumflex accent) immediately after the \"?\" is a\nshorthand equivalent to \"d-imnsx\".  Flags (except \"d\") may follow the caret to override\nit.  But a minus sign is not legal with it.\n\nNote that the \"a\", \"d\", \"l\", \"p\", and \"u\" modifiers are special in that they can only be\nenabled, not disabled, and the \"a\", \"d\", \"l\", and \"u\" modifiers are mutually exclusive:\nspecifying one de-specifies the others, and a maximum of one (or two \"a\"'s) may appear in\nthe construct.  Thus, for example, \"(?-p)\" will warn when compiled under \"use warnings\";\n\"(?-d:...)\" and \"(?dl:...)\" are fatal errors.\n\nNote also that the \"p\" modifier is special in that its presence anywhere in a pattern has\na global effect.\n\nHaving zero modifiers makes this a no-op (so why did you specify it, unless it's\ngenerated code), and starting in v5.30, warns under \"use re 'strict'\".\n\n\"(?:pattern)\"\n\"(?adluimnsx-imnsx:pattern)\"\n\"(?^aluimnsx:pattern)\"\nThis is for clustering, not capturing; it groups subexpressions like \"()\", but doesn't\nmake backreferences as \"()\" does.  So\n\n@fields = split(/\\b(?:a|b|c)\\b/)\n\nmatches the same field delimiters as\n\n@fields = split(/\\b(a|b|c)\\b/)\n\nbut doesn't spit out the delimiters themselves as extra fields (even though that's the\nbehaviour of \"split\" in perlfunc when its pattern contains capturing groups).  It's also\ncheaper not to capture characters if you don't need to.\n\nAny letters between \"?\" and \":\" act as flags modifiers as with \"(?adluimnsx-imnsx)\".  For\nexample,\n\n/(?s-i:more.*than).*million/i\n\nis equivalent to the more verbose\n\n/(?:(?s-i)more.*than).*million/i\n\nNote that any \"()\" constructs enclosed within this one will still capture unless the \"/n\"\nmodifier is in effect.\n\nLike the \"(?adlupimnsx-imnsx)\" construct, \"aa\" and \"a\" override each other, as do \"xx\"\nand \"x\".  They are not additive.  So, doing something like \"(?xx-x:foo)\" turns off all\n\"x\" behavior for matching \"foo\".\n\nStarting in Perl 5.14, a \"^\" (caret or circumflex accent) immediately after the \"?\" is a\nshorthand equivalent to \"d-imnsx\".  Any positive flags (except \"d\") may follow the caret,\nso\n\n(?^x:foo)\n\nis equivalent to\n\n(?x-imns:foo)\n\nThe caret tells Perl that this cluster doesn't inherit the flags of any surrounding\npattern, but uses the system defaults (\"d-imnsx\"), modified by any flags specified.\n\nThe caret allows for simpler stringification of compiled regular expressions.  These look\nlike\n\n(?^:pattern)\n\nwith any non-default flags appearing between the caret and the colon.  A test that looks\nat such stringification thus doesn't need to have the system default flags hard-coded in\nit, just the caret.  If new flags are added to Perl, the meaning of the caret's expansion\nwill change to include the default for those flags, so the test will still work,\nunchanged.\n\nSpecifying a negative flag after the caret is an error, as the flag is redundant.\n\nMnemonic for \"(?^...)\":  A fresh beginning since the usual use of a caret is to match at\nthe beginning.\n\n\"(?|pattern)\"\nThis is the \"branch reset\" pattern, which has the special property that the capture\ngroups are numbered from the same starting point in each alternation branch. It is\navailable starting from perl 5.10.0.\n\nCapture groups are numbered from left to right, but inside this construct the numbering\nis restarted for each branch.\n\nThe numbering within each branch will be as normal, and any groups following this\nconstruct will be numbered as though the construct contained only one branch, that being\nthe one with the most capture groups in it.\n\nThis construct is useful when you want to capture one of a number of alternative matches.\n\nConsider the following pattern.  The numbers underneath show in which group the captured\ncontent will be stored.\n\n# before  ---------------branch-reset----------- after\n/ ( a )  (?| x ( y ) z | (p (q) r) | (t) u (v) ) ( z ) /x\n# 1            2         2  3        2     3     4\n\nBe careful when using the branch reset pattern in combination with named captures. Named\ncaptures are implemented as being aliases to numbered groups holding the captures, and\nthat interferes with the implementation of the branch reset pattern. If you are using\nnamed captures in a branch reset pattern, it's best to use the same names, in the same\norder, in each of the alternations:\n\n/(?|  (?<a> x ) (?<b> y )\n|  (?<a> z ) (?<b> w )) /x\n\nNot doing so may lead to surprises:\n\n\"12\" =~ /(?| (?<a> \\d+ ) | (?<b> \\D+))/x;\nsay $+{a};    # Prints '12'\nsay $+{b};    # *Also* prints '12'.\n\nThe problem here is that both the group named \"a\" and the group named \"b\" are aliases for\nthe group belonging to $1.\n\nLookaround Assertions\nLookaround assertions are zero-width patterns which match a specific pattern without\nincluding it in $&. Positive assertions match when their subpattern matches, negative\nassertions match when their subpattern fails. Lookbehind matches text up to the current\nmatch position, lookahead matches text following the current match position.\n\n\"(?=pattern)\"\n\"(*pla:pattern)\"\n\"(*positivelookahead:pattern)\"\nA zero-width positive lookahead assertion.  For example, \"/\\w+(?=\\t)/\" matches a word\nfollowed by a tab, without including the tab in $&.\n\n\"(?!pattern)\"\n\"(*nla:pattern)\"\n\"(*negativelookahead:pattern)\"\nA zero-width negative lookahead assertion.  For example \"/foo(?!bar)/\" matches any\noccurrence of \"foo\" that isn't followed by \"bar\".  Note however that lookahead and\nlookbehind are NOT the same thing.  You cannot use this for lookbehind.\n\nIf you are looking for a \"bar\" that isn't preceded by a \"foo\", \"/(?!foo)bar/\" will\nnot do what you want.  That's because the \"(?!foo)\" is just saying that the next\nthing cannot be \"foo\"--and it's not, it's a \"bar\", so \"foobar\" will match.  Use\nlookbehind instead (see below).\n\n\"(?<=pattern)\"\n\"\\K\"\n\"(*plb:pattern)\"\n\"(*positivelookbehind:pattern)\"\nA zero-width positive lookbehind assertion.  For example, \"/(?<=\\t)\\w+/\" matches a\nword that follows a tab, without including the tab in $&.\n\nPrior to Perl 5.30, it worked only for fixed-width lookbehind, but starting in that\nrelease, it can handle variable lengths from 1 to 255 characters as an experimental\nfeature.  The feature is enabled automatically if you use a variable length\nlookbehind assertion, but will raise a warning at pattern compilation time, unless\nturned off, in the \"experimental::vlb\" category.  This is to warn you that the exact\nbehavior is subject to change should feedback from actual use in the field indicate\nto do so; or even complete removal if the problems found are not practically\nsurmountable.  You can achieve close to pre-5.30 behavior by fatalizing warnings in\nthis category.\n\nThere is a special form of this construct, called \"\\K\" (available since Perl 5.10.0),\nwhich causes the regex engine to \"keep\" everything it had matched prior to the \"\\K\"\nand not include it in $&. This effectively provides non-experimental variable-length\nlookbehind of any length.\n\nAnd, there is a technique that can be used to handle variable length lookbehinds on\nearlier releases, and longer than 255 characters.  It is described in\n<http://www.drregex.com/2019/02/variable-length-lookbehinds-actually.html>.\n\nNote that under \"/i\", a few single characters match two or three other characters.\nThis makes them variable length, and the 255 length applies to the maximum number of\ncharacters in the match.  For example \"qr/\\N{LATIN SMALL LETTER SHARP S}/i\" matches\nthe sequence \"ss\".  Your lookbehind assertion could contain 127 Sharp S characters\nunder \"/i\", but adding a 128th would generate a compilation error, as that could\nmatch 256 \"s\" characters in a row.\n\nThe use of \"\\K\" inside of another lookaround assertion is allowed, but the behaviour\nis currently not well defined.\n\nFor various reasons \"\\K\" may be significantly more efficient than the equivalent\n\"(?<=...)\" construct, and it is especially useful in situations where you want to\nefficiently remove something following something else in a string. For instance\n\ns/(foo)bar/$1/g;\n\ncan be rewritten as the much more efficient\n\ns/foo\\Kbar//g;\n\nUse of the non-greedy modifier \"?\" may not give you the expected results if it is\nwithin a capturing group within the construct.\n\n\"(?<!pattern)\"\n\"(*nlb:pattern)\"\n\"(*negativelookbehind:pattern)\"\nA zero-width negative lookbehind assertion.  For example \"/(?<!bar)foo/\" matches any\noccurrence of \"foo\" that does not follow \"bar\".\n\nPrior to Perl 5.30, it worked only for fixed-width lookbehind, but starting in that\nrelease, it can handle variable lengths from 1 to 255 characters as an experimental\nfeature.  The feature is enabled automatically if you use a variable length\nlookbehind assertion, but will raise a warning at pattern compilation time, unless\nturned off, in the \"experimental::vlb\" category.  This is to warn you that the exact\nbehavior is subject to change should feedback from actual use in the field indicate\nto do so; or even complete removal if the problems found are not practically\nsurmountable.  You can achieve close to pre-5.30 behavior by fatalizing warnings in\nthis category.\n\nThere is a technique that can be used to handle variable length lookbehinds on\nearlier releases, and longer than 255 characters.  It is described in\n<http://www.drregex.com/2019/02/variable-length-lookbehinds-actually.html>.\n\nNote that under \"/i\", a few single characters match two or three other characters.\nThis makes them variable length, and the 255 length applies to the maximum number of\ncharacters in the match.  For example \"qr/\\N{LATIN SMALL LETTER SHARP S}/i\" matches\nthe sequence \"ss\".  Your lookbehind assertion could contain 127 Sharp S characters\nunder \"/i\", but adding a 128th would generate a compilation error, as that could\nmatch 256 \"s\" characters in a row.\n\nUse of the non-greedy modifier \"?\" may not give you the expected results if it is\nwithin a capturing group within the construct.\n\n\"(?<NAME>pattern)\"\n\"(?'NAME'pattern)\"\nA named capture group. Identical in every respect to normal capturing parentheses \"()\"\nbut for the additional fact that the group can be referred to by name in various regular\nexpression constructs (like \"\\g{NAME}\") and can be accessed by name after a successful\nmatch via \"%+\" or \"%-\". See perlvar for more details on the \"%+\" and \"%-\" hashes.\n\nIf multiple distinct capture groups have the same name, then $+{NAME} will refer to the\nleftmost defined group in the match.\n\nThe forms \"(?'NAME'pattern)\" and \"(?<NAME>pattern)\" are equivalent.\n\nNOTE: While the notation of this construct is the same as the similar function in .NET\nregexes, the behavior is not. In Perl the groups are numbered sequentially regardless of\nbeing named or not. Thus in the pattern\n\n/(x)(?<foo>y)(z)/\n\n$+{foo} will be the same as $2, and $3 will contain 'z' instead of the opposite which is\nwhat a .NET regex hacker might expect.\n\nCurrently NAME is restricted to simple identifiers only.  In other words, it must match\n\"/^[A-Za-z][A-Za-z0-9]*\\z/\" or its Unicode extension (see utf8), though it isn't\nextended by the locale (see perllocale).\n\nNOTE: In order to make things easier for programmers with experience with the Python or\nPCRE regex engines, the pattern \"(?P<NAME>pattern)\" may be used instead of\n\"(?<NAME>pattern)\"; however this form does not support the use of single quotes as a\ndelimiter for the name.\n\n\"\\k<NAME>\"\n\"\\k'NAME'\"\n\"\\k{NAME}\"\nNamed backreference. Similar to numeric backreferences, except that the group is\ndesignated by name and not number. If multiple groups have the same name then it refers\nto the leftmost defined group in the current match.\n\nIt is an error to refer to a name not defined by a \"(?<NAME>)\" earlier in the pattern.\n\nAll three forms are equivalent, although with \"\\k{ NAME }\", you may optionally have\nblanks within but adjacent to the braces, as shown.\n\nNOTE: In order to make things easier for programmers with experience with the Python or\nPCRE regex engines, the pattern \"(?P=NAME)\" may be used instead of \"\\k<NAME>\".\n\n\"(?{ code })\"\nWARNING: Using this feature safely requires that you understand its limitations.  Code\nexecuted that has side effects may not perform identically from version to version due to\nthe effect of future optimisations in the regex engine.  For more information on this,\nsee \"Embedded Code Execution Frequency\".\n\nThis zero-width assertion executes any embedded Perl code.  It always succeeds, and its\nreturn value is set as $^R.\n\nIn literal patterns, the code is parsed at the same time as the surrounding code. While\nwithin the pattern, control is passed temporarily back to the perl parser, until the\nlogically-balancing closing brace is encountered. This is similar to the way that an\narray index expression in a literal string is handled, for example\n\n\"abc$array[ 1 + f('[') + g()]def\"\n\nIn particular, braces do not need to be balanced:\n\ns/abc(?{ f('{'); })/def/\n\nEven in a pattern that is interpolated and compiled at run-time, literal code blocks will\nbe compiled once, at perl compile time; the following prints \"ABCD\":\n\nprint \"D\";\nmy $qr = qr/(?{ BEGIN { print \"A\" } })/;\nmy $foo = \"foo\";\n/$foo$qr(?{ BEGIN { print \"B\" } })/;\nBEGIN { print \"C\" }\n\nIn patterns where the text of the code is derived from run-time information rather than\nappearing literally in a source code /pattern/, the code is compiled at the same time\nthat the pattern is compiled, and for reasons of security, \"use re 'eval'\" must be in\nscope. This is to stop user-supplied patterns containing code snippets from being\nexecutable.\n\nIn situations where you need to enable this with \"use re 'eval'\", you should also have\ntaint checking enabled.  Better yet, use the carefully constrained evaluation within a\nSafe compartment.  See perlsec for details about both these mechanisms.\n\nFrom the viewpoint of parsing, lexical variable scope and closures,\n\n/AAA(?{ BBB })CCC/\n\nbehaves approximately like\n\n/AAA/ && do { BBB } && /CCC/\n\nSimilarly,\n\nqr/AAA(?{ BBB })CCC/\n\nbehaves approximately like\n\nsub { /AAA/ && do { BBB } && /CCC/ }\n\nIn particular:\n\n{ my $i = 1; $r = qr/(?{ print $i })/ }\nmy $i = 2;\n/$r/; # prints \"1\"\n\nInside a \"(?{...})\" block, $ refers to the string the regular expression is matching\nagainst. You can also use \"pos()\" to know what is the current position of matching within\nthis string.\n\nThe code block introduces a new scope from the perspective of lexical variable\ndeclarations, but not from the perspective of \"local\" and similar localizing behaviours.\nSo later code blocks within the same pattern will still see the values which were\nlocalized in earlier blocks.  These accumulated localizations are undone either at the\nend of a successful match, or if the assertion is backtracked (compare \"Backtracking\").\nFor example,\n\n$ = 'a' x 8;\nm<\n(?{ $cnt = 0 })               # Initialize $cnt.\n(\na\n(?{\nlocal $cnt = $cnt + 1;  # Update $cnt,\n# backtracking-safe.\n})\n)*\naaaa\n(?{ $res = $cnt })            # On success copy to\n# non-localized location.\n>x;\n\nwill initially increment $cnt up to 8; then during backtracking, its value will be\nunwound back to 4, which is the value assigned to $res.  At the end of the regex\nexecution, $cnt will be wound back to its initial value of 0.\n\nThis assertion may be used as the condition in a\n\n(?(condition)yes-pattern|no-pattern)\n\nswitch.  If not used in this way, the result of evaluation of code is put into the\nspecial variable $^R.  This happens immediately, so $^R can be used from other \"(?{ code\n})\" assertions inside the same regular expression.\n\nThe assignment to $^R above is properly localized, so the old value of $^R is restored if\nthe assertion is backtracked; compare \"Backtracking\".\n\nNote that the special variable $^N  is particularly useful with code blocks to capture\nthe results of submatches in variables without having to keep track of the number of\nnested parentheses. For example:\n\n$ = \"The brown fox jumps over the lazy dog\";\n/the (\\S+)(?{ $color = $^N }) (\\S+)(?{ $animal = $^N })/i;\nprint \"color = $color, animal = $animal\\n\";\n\n\"(??{ code })\"\nWARNING: Using this feature safely requires that you understand its limitations.  Code\nexecuted that has side effects may not perform identically from version to version due to\nthe effect of future optimisations in the regex engine.  For more information on this,\nsee \"Embedded Code Execution Frequency\".\n\nThis is a \"postponed\" regular subexpression.  It behaves in exactly the same way as a\n\"(?{ code })\" code block as described above, except that its return value, rather than\nbeing assigned to $^R, is treated as a pattern, compiled if it's a string (or used as-is\nif its a qr// object), then matched as if it were inserted instead of this construct.\n\nDuring the matching of this sub-pattern, it has its own set of captures which are valid\nduring the sub-match, but are discarded once control returns to the main pattern. For\nexample, the following matches, with the inner pattern capturing \"B\" and matching \"BB\",\nwhile the outer pattern captures \"A\";\n\nmy $inner = '(.)\\1';\n\"ABBA\" =~ /^(.)(??{ $inner })\\1/;\nprint $1; # prints \"A\";\n\nNote that this means that  there is no way for the inner pattern to refer to a capture\ngroup defined outside.  (The code block itself can use $1, etc., to refer to the\nenclosing pattern's capture groups.)  Thus, although\n\n('a' x 100)=~/(??{'(.)' x 100})/\n\nwill match, it will not set $1 on exit.\n\nThe following pattern matches a parenthesized group:\n\n$re = qr{\n\\(\n(?:\n(?> [^()]+ )  # Non-parens without backtracking\n|\n(??{ $re })   # Group with matching parens\n)*\n\\)\n}x;\n\nSee also \"(?PARNO)\" for a different, more efficient way to accomplish the same task.\n\nExecuting a postponed regular expression too many times without consuming any input\nstring will also result in a fatal error.  The depth at which that happens is compiled\ninto perl, so it can be changed with a custom build.\n\n\"(?PARNO)\" \"(?-PARNO)\" \"(?+PARNO)\" \"(?R)\" \"(?0)\"\nRecursive subpattern. Treat the contents of a given capture buffer in the current pattern\nas an independent subpattern and attempt to match it at the current position in the\nstring. Information about capture state from the caller for things like backreferences is\navailable to the subpattern, but capture buffers set by the subpattern are not visible to\nthe caller.\n\nSimilar to \"(??{ code })\" except that it does not involve executing any code or\npotentially compiling a returned pattern string; instead it treats the part of the\ncurrent pattern contained within a specified capture group as an independent pattern that\nmust match at the current position. Also different is the treatment of capture buffers,\nunlike \"(??{ code })\" recursive patterns have access to their caller's match state, so\none can use backreferences safely.\n\nPARNO is a sequence of digits (not starting with 0) whose value reflects the paren-number\nof the capture group to recurse to. \"(?R)\" recurses to the beginning of the whole\npattern. \"(?0)\" is an alternate syntax for \"(?R)\". If PARNO is preceded by a plus or\nminus sign then it is assumed to be relative, with negative numbers indicating preceding\ncapture groups and positive ones following. Thus \"(?-1)\" refers to the most recently\ndeclared group, and \"(?+1)\" indicates the next group to be declared.  Note that the\ncounting for relative recursion differs from that of relative backreferences, in that\nwith recursion unclosed groups are included.\n\nThe following pattern matches a function \"foo()\" which may contain balanced parentheses\nas the argument.\n\n$re = qr{ (                   # paren group 1 (full function)\nfoo\n(                 # paren group 2 (parens)\n\\(\n(             # paren group 3 (contents of parens)\n(?:\n(?> [^()]+ ) # Non-parens without backtracking\n|\n(?2)         # Recurse to start of paren group 2\n)*\n)\n\\)\n)\n)\n}x;\n\nIf the pattern was used as follows\n\n'foo(bar(baz)+baz(bop))'=~/$re/\nand print \"\\$1 = $1\\n\",\n\"\\$2 = $2\\n\",\n\"\\$3 = $3\\n\";\n\nthe output produced should be the following:\n\n$1 = foo(bar(baz)+baz(bop))\n$2 = (bar(baz)+baz(bop))\n$3 = bar(baz)+baz(bop)\n\nIf there is no corresponding capture group defined, then it is a fatal error.  Recursing\ndeeply without consuming any input string will also result in a fatal error.  The depth\nat which that happens is compiled into perl, so it can be changed with a custom build.\n\nThe following shows how using negative indexing can make it easier to embed recursive\npatterns inside of a \"qr//\" construct for later use:\n\nmy $parens = qr/(\\((?:[^()]++|(?-1))*+\\))/;\nif (/foo $parens \\s+ \\+ \\s+ bar $parens/x) {\n# do something here...\n}\n\nNote that this pattern does not behave the same way as the equivalent PCRE or Python\nconstruct of the same form. In Perl you can backtrack into a recursed group, in PCRE and\nPython the recursed into group is treated as atomic. Also, modifiers are resolved at\ncompile time, so constructs like \"(?i:(?1))\" or \"(?:(?i)(?1))\" do not affect how the sub-\npattern will be processed.\n\n\"(?&NAME)\"\nRecurse to a named subpattern. Identical to \"(?PARNO)\" except that the parenthesis to\nrecurse to is determined by name. If multiple parentheses have the same name, then it\nrecurses to the leftmost.\n\nIt is an error to refer to a name that is not declared somewhere in the pattern.\n\nNOTE: In order to make things easier for programmers with experience with the Python or\nPCRE regex engines the pattern \"(?P>NAME)\" may be used instead of \"(?&NAME)\".\n\n\"(?(condition)yes-pattern|no-pattern)\"\n\"(?(condition)yes-pattern)\"\nConditional expression. Matches yes-pattern if condition yields a true value, matches no-\npattern otherwise. A missing pattern always matches.\n\n\"(condition)\" should be one of:\n\nan integer in parentheses\n(which is valid if the corresponding pair of parentheses matched);\n\na lookahead/lookbehind/evaluate zero-width assertion;\na name in angle brackets or single quotes\n(which is valid if a group with the given name matched);\n\nthe special symbol \"(R)\"\n(true when evaluated inside of recursion or eval).  Additionally the \"R\" may be\nfollowed by a number, (which will be true when evaluated when recursing inside of the\nappropriate group), or by \"&NAME\", in which case it will be true only when evaluated\nduring recursion in the named group.\n\nHere's a summary of the possible predicates:\n\n\"(1)\" \"(2)\" ...\nChecks if the numbered capturing group has matched something.  Full syntax:\n\"(?(1)then|else)\"\n\n\"(<NAME>)\" \"('NAME')\"\nChecks if a group with the given name has matched something.  Full syntax:\n\"(?(<name>)then|else)\"\n\n\"(?=...)\" \"(?!...)\" \"(?<=...)\" \"(?<!...)\"\nChecks whether the pattern matches (or does not match, for the \"!\"  variants).  Full\nsyntax: \"(?(?=lookahead)then|else)\"\n\n\"(?{ CODE })\"\nTreats the return value of the code block as the condition.  Full syntax: \"(?(?{ code\n})then|else)\"\n\n\"(R)\"\nChecks if the expression has been evaluated inside of recursion.  Full syntax:\n\"(?(R)then|else)\"\n\n\"(R1)\" \"(R2)\" ...\nChecks if the expression has been evaluated while executing directly inside of the\nn-th capture group. This check is the regex equivalent of\n\nif ((caller(0))[3] eq 'subname') { ... }\n\nIn other words, it does not check the full recursion stack.\n\nFull syntax: \"(?(R1)then|else)\"\n\n\"(R&NAME)\"\nSimilar to \"(R1)\", this predicate checks to see if we're executing directly inside of\nthe leftmost group with a given name (this is the same logic used by \"(?&NAME)\" to\ndisambiguate). It does not check the full stack, but only the name of the innermost\nactive recursion.  Full syntax: \"(?(R&name)then|else)\"\n\n\"(DEFINE)\"\nIn this case, the yes-pattern is never directly executed, and no no-pattern is\nallowed. Similar in spirit to \"(?{0})\" but more efficient.  See below for details.\nFull syntax: \"(?(DEFINE)definitions...)\"\n\nFor example:\n\nm{ ( \\( )?\n[^()]+\n(?(1) \\) )\n}x\n\nmatches a chunk of non-parentheses, possibly included in parentheses themselves.\n\nA special form is the \"(DEFINE)\" predicate, which never executes its yes-pattern\ndirectly, and does not allow a no-pattern. This allows one to define subpatterns which\nwill be executed only by the recursion mechanism.  This way, you can define a set of\nregular expression rules that can be bundled into any pattern you choose.\n\nIt is recommended that for this usage you put the DEFINE block at the end of the pattern,\nand that you name any subpatterns defined within it.\n\nAlso, it's worth noting that patterns defined this way probably will not be as efficient,\nas the optimizer is not very clever about handling them.\n\nAn example of how this might be used is as follows:\n\n/(?<NAME>(?&NAMEPAT))(?<ADDR>(?&ADDRESSPAT))\n(?(DEFINE)\n(?<NAMEPAT>....)\n(?<ADDRESSPAT>....)\n)/x\n\nNote that capture groups matched inside of recursion are not accessible after the\nrecursion returns, so the extra layer of capturing groups is necessary. Thus $+{NAMEPAT}\nwould not be defined even though $+{NAME} would be.\n\nFinally, keep in mind that subpatterns created inside a DEFINE block count towards the\nabsolute and relative number of captures, so this:\n\nmy @captures = \"a\" =~ /(.)                  # First capture\n(?(DEFINE)\n(?<EXAMPLE> 1 )  # Second capture\n)/x;\nsay scalar @captures;\n\nWill output 2, not 1. This is particularly important if you intend to compile the\ndefinitions with the \"qr//\" operator, and later interpolate them in another pattern.\n\n\"(?>pattern)\"\n\"(*atomic:pattern)\"\nAn \"independent\" subexpression, one which matches the substring that a standalone pattern\nwould match if anchored at the given position, and it matches nothing other than this\nsubstring.  This construct is useful for optimizations of what would otherwise be\n\"eternal\" matches, because it will not backtrack (see \"Backtracking\").  It may also be\nuseful in places where the \"grab all you can, and do not give anything back\" semantic is\ndesirable.\n\nFor example: \"^(?>a*)ab\" will never match, since \"(?>a*)\" (anchored at the beginning of\nstring, as above) will match all characters \"a\" at the beginning of string, leaving no\n\"a\" for \"ab\" to match.  In contrast, \"a*ab\" will match the same as \"a+b\", since the match\nof the subgroup \"a*\" is influenced by the following group \"ab\" (see \"Backtracking\").  In\nparticular, \"a*\" inside \"a*ab\" will match fewer characters than a standalone \"a*\", since\nthis makes the tail match.\n\n\"(?>pattern)\" does not disable backtracking altogether once it has matched. It is still\npossible to backtrack past the construct, but not into it. So \"((?>a*)|(?>b*))ar\" will\nstill match \"bar\".\n\nAn effect similar to \"(?>pattern)\" may be achieved by writing \"(?=(pattern))\\g{-1}\".\nThis matches the same substring as a standalone \"a+\", and the following \"\\g{-1}\" eats the\nmatched string; it therefore makes a zero-length assertion into an analogue of \"(?>...)\".\n(The difference between these two constructs is that the second one uses a capturing\ngroup, thus shifting ordinals of backreferences in the rest of a regular expression.)\n\nConsider this pattern:\n\nm{ \\(\n(\n[^()]+           # x+\n|\n\\( [^()]* \\)\n)+\n\\)\n}x\n\nThat will efficiently match a nonempty group with matching parentheses two levels deep or\nless.  However, if there is no such group, it will take virtually forever on a long\nstring.  That's because there are so many different ways to split a long string into\nseveral substrings.  This is what \"(.+)+\" is doing, and \"(.+)+\" is similar to a\nsubpattern of the above pattern.  Consider how the pattern above detects no-match on\n\"((()aaaaaaaaaaaaaaaaaa\" in several seconds, but that each extra letter doubles this\ntime.  This exponential performance will make it appear that your program has hung.\nHowever, a tiny change to this pattern\n\nm{ \\(\n(\n(?> [^()]+ )        # change x+ above to (?> x+ )\n|\n\\( [^()]* \\)\n)+\n\\)\n}x\n\nwhich uses \"(?>...)\" matches exactly when the one above does (verifying this yourself\nwould be a productive exercise), but finishes in a fourth the time when used on a similar\nstring with 1000000 \"a\"s.  Be aware, however, that, when this construct is followed by a\nquantifier, it currently triggers a warning message under the \"use warnings\" pragma or -w\nswitch saying it \"matches null string many times in regex\".\n\nOn simple groups, such as the pattern \"(?> [^()]+ )\", a comparable effect may be achieved\nby negative lookahead, as in \"[^()]+ (?! [^()] )\".  This was only 4 times slower on a\nstring with 1000000 \"a\"s.\n\nThe \"grab all you can, and do not give anything back\" semantic is desirable in many\nsituations where on the first sight a simple \"()*\" looks like the correct solution.\nSuppose we parse text with comments being delimited by \"#\" followed by some optional\n(horizontal) whitespace.  Contrary to its appearance, \"#[ \\t]*\" is not the correct\nsubexpression to match the comment delimiter, because it may \"give up\" some whitespace if\nthe remainder of the pattern can be made to match that way.  The correct answer is either\none of these:\n\n(?>#[ \\t]*)\n#[ \\t]*(?![ \\t])\n\nFor example, to grab non-empty comments into $1, one should use either one of these:\n\n/ (?> \\# [ \\t]* ) (        .+ ) /x;\n/     \\# [ \\t]*   ( [^ \\t] .* ) /x;\n\nWhich one you pick depends on which of these expressions better reflects the above\nspecification of comments.\n\nIn some literature this construct is called \"atomic matching\" or \"possessive matching\".\n\nPossessive quantifiers are equivalent to putting the item they are applied to inside of\none of these constructs. The following equivalences apply:\n\nQuantifier Form     Bracketing Form\n---------------     ---------------\nPAT*+               (?>PAT*)\nPAT++               (?>PAT+)\nPAT?+               (?>PAT?)\nPAT{min,max}+       (?>PAT{min,max})\n\nNested \"(?>...)\" constructs are not no-ops, even if at first glance they might seem to\nbe.  This is because the nested \"(?>...)\" can restrict internal backtracking that\notherwise might occur.  For example,\n\n\"abc\" =~ /(?>a[bc]*c)/\n\nmatches, but\n\n\"abc\" =~ /(?>a(?>[bc]*)c)/\n\ndoes not.\n\n\"(?[ ])\"\nSee \"Extended Bracketed Character Classes\" in perlrecharclass.\n\nNote that this feature is currently experimental; using it yields a warning in the\n\"experimental::regexsets\" category.\n"
                    },
                    {
                        "name": "Backtracking",
                        "content": "NOTE: This section presents an abstract approximation of regular expression behavior.  For a\nmore rigorous (and complicated) view of the rules involved in selecting a match among\npossible alternatives, see \"Combining RE Pieces\".\n\nA fundamental feature of regular expression matching involves the notion called backtracking,\nwhich is currently used (when needed) by all regular non-possessive expression quantifiers,\nnamely \"*\", \"*?\", \"+\", \"+?\", \"{n,m}\", and \"{n,m}?\".  Backtracking is often optimized\ninternally, but the general principle outlined here is valid.\n\nFor a regular expression to match, the entire regular expression must match, not just part of\nit.  So if the beginning of a pattern containing a quantifier succeeds in a way that causes\nlater parts in the pattern to fail, the matching engine backs up and recalculates the\nbeginning part--that's why it's called backtracking.\n\nHere is an example of backtracking:  Let's say you want to find the word following \"foo\" in\nthe string \"Food is on the foo table.\":\n\n$ = \"Food is on the foo table.\";\nif ( /\\b(foo)\\s+(\\w+)/i ) {\nprint \"$2 follows $1.\\n\";\n}\n\nWhen the match runs, the first part of the regular expression (\"\\b(foo)\") finds a possible\nmatch right at the beginning of the string, and loads up $1 with \"Foo\".  However, as soon as\nthe matching engine sees that there's no whitespace following the \"Foo\" that it had saved in\n$1, it realizes its mistake and starts over again one character after where it had the\ntentative match.  This time it goes all the way until the next occurrence of \"foo\". The\ncomplete regular expression matches this time, and you get the expected output of \"table\nfollows foo.\"\n\nSometimes minimal matching can help a lot.  Imagine you'd like to match everything between\n\"foo\" and \"bar\".  Initially, you write something like this:\n\n$ =  \"The food is under the bar in the barn.\";\nif ( /foo(.*)bar/ ) {\nprint \"got <$1>\\n\";\n}\n\nWhich perhaps unexpectedly yields:\n\ngot <d is under the bar in the >\n\nThat's because \".*\" was greedy, so you get everything between the first \"foo\" and the last\n\"bar\".  Here it's more effective to use minimal matching to make sure you get the text\nbetween a \"foo\" and the first \"bar\" thereafter.\n\nif ( /foo(.*?)bar/ ) { print \"got <$1>\\n\" }\ngot <d is under the >\n\nHere's another example. Let's say you'd like to match a number at the end of a string, and\nyou also want to keep the preceding part of the match.  So you write this:\n\n$ = \"I have 2 numbers: 53147\";\nif ( /(.*)(\\d*)/ ) {                                # Wrong!\nprint \"Beginning is <$1>, number is <$2>.\\n\";\n}\n\nThat won't work at all, because \".*\" was greedy and gobbled up the whole string. As \"\\d*\" can\nmatch on an empty string the complete regular expression matched successfully.\n\nBeginning is <I have 2 numbers: 53147>, number is <>.\n\nHere are some variants, most of which don't work:\n\n$ = \"I have 2 numbers: 53147\";\n@pats = qw{\n(.*)(\\d*)\n(.*)(\\d+)\n(.*?)(\\d*)\n(.*?)(\\d+)\n(.*)(\\d+)$\n(.*?)(\\d+)$\n(.*)\\b(\\d+)$\n(.*\\D)(\\d+)$\n};\n\nfor $pat (@pats) {\nprintf \"%-12s \", $pat;\nif ( /$pat/ ) {\nprint \"<$1> <$2>\\n\";\n} else {\nprint \"FAIL\\n\";\n}\n}\n\nThat will print out:\n\n(.*)(\\d*)    <I have 2 numbers: 53147> <>\n(.*)(\\d+)    <I have 2 numbers: 5314> <7>\n(.*?)(\\d*)   <> <>\n(.*?)(\\d+)   <I have > <2>\n(.*)(\\d+)$   <I have 2 numbers: 5314> <7>\n(.*?)(\\d+)$  <I have 2 numbers: > <53147>\n(.*)\\b(\\d+)$ <I have 2 numbers: > <53147>\n(.*\\D)(\\d+)$ <I have 2 numbers: > <53147>\n\nAs you see, this can be a bit tricky.  It's important to realize that a regular expression is\nmerely a set of assertions that gives a definition of success.  There may be 0, 1, or several\ndifferent ways that the definition might succeed against a particular string.  And if there\nare multiple ways it might succeed, you need to understand backtracking to know which variety\nof success you will achieve.\n\nWhen using lookahead assertions and negations, this can all get even trickier.  Imagine you'd\nlike to find a sequence of non-digits not followed by \"123\".  You might try to write that as\n\n$ = \"ABC123\";\nif ( /^\\D*(?!123)/ ) {                # Wrong!\nprint \"Yup, no 123 in $\\n\";\n}\n\nBut that isn't going to match; at least, not the way you're hoping.  It claims that there is\nno 123 in the string.  Here's a clearer picture of why that pattern matches, contrary to\npopular expectations:\n\n$x = 'ABC123';\n$y = 'ABC445';\n\nprint \"1: got $1\\n\" if $x =~ /^(ABC)(?!123)/;\nprint \"2: got $1\\n\" if $y =~ /^(ABC)(?!123)/;\n\nprint \"3: got $1\\n\" if $x =~ /^(\\D*)(?!123)/;\nprint \"4: got $1\\n\" if $y =~ /^(\\D*)(?!123)/;\n\nThis prints\n\n2: got ABC\n3: got AB\n4: got ABC\n\nYou might have expected test 3 to fail because it seems to a more general purpose version of\ntest 1.  The important difference between them is that test 3 contains a quantifier (\"\\D*\")\nand so can use backtracking, whereas test 1 will not.  What's happening is that you've asked\n\"Is it true that at the start of $x, following 0 or more non-digits, you have something\nthat's not 123?\"  If the pattern matcher had let \"\\D*\" expand to \"ABC\", this would have\ncaused the whole pattern to fail.\n\nThe search engine will initially match \"\\D*\" with \"ABC\".  Then it will try to match \"(?!123)\"\nwith \"123\", which fails.  But because a quantifier (\"\\D*\") has been used in the regular\nexpression, the search engine can backtrack and retry the match differently in the hope of\nmatching the complete regular expression.\n\nThe pattern really, really wants to succeed, so it uses the standard pattern back-off-and-\nretry and lets \"\\D*\" expand to just \"AB\" this time.  Now there's indeed something following\n\"AB\" that is not \"123\".  It's \"C123\", which suffices.\n\nWe can deal with this by using both an assertion and a negation.  We'll say that the first\npart in $1 must be followed both by a digit and by something that's not \"123\".  Remember that\nthe lookaheads are zero-width expressions--they only look, but don't consume any of the\nstring in their match.  So rewriting this way produces what you'd expect; that is, case 5\nwill fail, but case 6 succeeds:\n\nprint \"5: got $1\\n\" if $x =~ /^(\\D*)(?=\\d)(?!123)/;\nprint \"6: got $1\\n\" if $y =~ /^(\\D*)(?=\\d)(?!123)/;\n\n6: got ABC\n\nIn other words, the two zero-width assertions next to each other work as though they're ANDed\ntogether, just as you'd use any built-in assertions:  \"/^$/\" matches only if you're at the\nbeginning of the line AND the end of the line simultaneously.  The deeper underlying truth is\nthat juxtaposition in regular expressions always means AND, except when you write an explicit\nOR using the vertical bar.  \"/ab/\" means match \"a\" AND (then) match \"b\", although the\nattempted matches are made at different positions because \"a\" is not a zero-width assertion,\nbut a one-width assertion.\n\nWARNING: Particularly complicated regular expressions can take exponential time to solve\nbecause of the immense number of possible ways they can use backtracking to try for a match.\nFor example, without internal optimizations done by the regular expression engine, this will\ntake a painfully long time to run:\n\n'aaaaaaaaaaaa' =~ /((a{0,5}){0,5})*[c]/\n\nAnd if you used \"*\"'s in the internal groups instead of limiting them to 0 through 5 matches,\nthen it would take forever--or until you ran out of stack space.  Moreover, these internal\noptimizations are not always applicable.  For example, if you put \"{0,5}\" instead of \"*\" on\nthe external group, no current optimization is applicable, and the match takes a long time to\nfinish.\n\nA powerful tool for optimizing such beasts is what is known as an \"independent group\", which\ndoes not backtrack (see \"(?>pattern)\").  Note also that zero-length lookahead/lookbehind\nassertions will not backtrack to make the tail match, since they are in \"logical\" context:\nonly whether they match is considered relevant.  For an example where side-effects of\nlookahead might have influenced the following match, see \"(?>pattern)\".\n"
                    },
                    {
                        "name": "Script Runs",
                        "content": "A script run is basically a sequence of characters, all from the same Unicode script (see\n\"Scripts\" in perlunicode), such as Latin or Greek.  In most places a single word would never\nbe written in multiple scripts, unless it is a spoofing attack.  An infamous example, is\n\npaypal.com\n\nThose letters could all be Latin (as in the example just above), or they could be all\nCyrillic (except for the dot), or they could be a mixture of the two.  In the case of an\ninternet address the \".com\" would be in Latin, And any Cyrillic ones would cause it to be a\nmixture, not a script run.  Someone clicking on such a link would not be directed to the real\nPaypal website, but an attacker would craft a look-alike one to attempt to gather sensitive\ninformation from the person.\n\nStarting in Perl 5.28, it is now easy to detect strings that aren't script runs.  Simply\nenclose just about any pattern like either of these:\n\n(*scriptrun:pattern)\n(*sr:pattern)\n\nWhat happens is that after pattern succeeds in matching, it is subjected to the additional\ncriterion that every character in it must be from the same script (see exceptions below).  If\nthis isn't true, backtracking occurs until something all in the same script is found that\nmatches, or all possibilities are exhausted.  This can cause a lot of backtracking, but\ngenerally, only malicious input will result in this, though the slow down could cause a\ndenial of service attack.  If your needs permit, it is best to make the pattern atomic to cut\ndown on the amount of backtracking.  This is so likely to be what you want, that instead of\nwriting this:\n\n(*scriptrun:(?>pattern))\n\nyou can write either of these:\n\n(*atomicscriptrun:pattern)\n(*asr:pattern)\n\n(See \"(?>pattern)\".)\n\nIn Taiwan, Japan, and Korea, it is common for text to have a mixture of characters from their\nnative scripts and base Chinese.  Perl follows Unicode's UTS 39\n(<https://unicode.org/reports/tr39/>) Unicode Security Mechanisms in allowing such mixtures.\nFor example, the Japanese scripts Katakana and Hiragana are commonly mixed together in\npractice, along with some Chinese characters, and hence are treated as being in a single\nscript run by Perl.\n\nThe rules used for matching decimal digits are slightly stricter.  Many scripts have their\nown sets of digits equivalent to the Western 0 through 9 ones.  A few, such as Arabic, have\nmore than one set.  For a string to be considered a script run, all digits in it must come\nfrom the same set of ten, as determined by the first digit encountered.  As an example,\n\nqr/(*scriptrun: \\d+ \\b )/x\n\nguarantees that the digits matched will all be from the same set of 10.  You won't get a\nlook-alike digit from a different script that has a different value than what it appears to\nbe.\n\nUnicode has three pseudo scripts that are handled specially.\n\n\"Unknown\" is applied to code points whose meaning has yet to be determined.  Perl currently\nwill match as a script run, any single character string consisting of one of these code\npoints.  But any string longer than one code point containing one of these will not be\nconsidered a script run.\n\n\"Inherited\" is applied to characters that modify another, such as an accent of some type.\nThese are considered to be in the script of the master character, and so never cause a script\nrun to not match.\n\nThe other one is \"Common\".  This consists of mostly punctuation, emoji, and characters used\nin mathematics and music, the ASCII digits 0 through 9, and full-width forms of these digits.\nThese characters can appear intermixed in text in many of the world's scripts.  These also\ndon't cause a script run to not match.  But like other scripts, all digits in a run must come\nfrom the same set of 10.\n\nThis construct is non-capturing.  You can add parentheses to pattern to capture, if desired.\nYou will have to do this if you plan to use \"(*ACCEPT) (*ACCEPT:arg)\" and not have it bypass\nthe script run checking.\n\nThe \"ScriptExtensions\" property as modified by UTS 39 (<https://unicode.org/reports/tr39/>)\nis used as the basis for this feature.\n\nTo summarize,\n\n•   All length 0 or length 1 sequences are script runs.\n\n•   A longer sequence is a script run if and only if all of the following conditions are met:\n\n\n\n1.  No code point in the sequence has the \"ScriptExtension\" property of \"Unknown\".\n\nThis currently means that all code points in the sequence have been assigned by\nUnicode to be characters that aren't private use nor surrogate code points.\n\n2.  All characters in the sequence come from the Common script and/or the Inherited\nscript and/or a single other script.\n\nThe script of a character is determined by the \"ScriptExtensions\" property as\nmodified by UTS 39 (<https://unicode.org/reports/tr39/>), as described above.\n\n3.  All decimal digits in the sequence come from the same block of 10 consecutive digits.\n"
                    },
                    {
                        "name": "Special Backtracking Control Verbs",
                        "content": "These special patterns are generally of the form \"(*VERB:arg)\". Unless otherwise stated the\narg argument is optional; in some cases, it is mandatory.\n\nAny pattern containing a special backtracking verb that allows an argument has the special\nbehaviour that when executed it sets the current package's $REGERROR and $REGMARK variables.\nWhen doing so the following rules apply:\n\nOn failure, the $REGERROR variable will be set to the arg value of the verb pattern, if the\nverb was involved in the failure of the match. If the arg part of the pattern was omitted,\nthen $REGERROR will be set to the name of the last \"(*MARK:NAME)\" pattern executed, or to\nTRUE if there was none. Also, the $REGMARK variable will be set to FALSE.\n\nOn a successful match, the $REGERROR variable will be set to FALSE, and the $REGMARK variable\nwill be set to the name of the last \"(*MARK:NAME)\" pattern executed.  See the explanation for\nthe \"(*MARK:NAME)\" verb below for more details.\n\nNOTE: $REGERROR and $REGMARK are not magic variables like $1 and most other regex-related\nvariables. They are not local to a scope, nor readonly, but instead are volatile package\nvariables similar to $AUTOLOAD.  They are set in the package containing the code that\nexecuted the regex (rather than the one that compiled it, where those differ).  If necessary,\nyou can use \"local\" to localize changes to these variables to a specific scope before\nexecuting a regex.\n\nIf a pattern does not contain a special backtracking verb that allows an argument, then\n$REGERROR and $REGMARK are not touched at all.\n\nVerbs\n\"(*PRUNE)\" \"(*PRUNE:NAME)\"\nThis zero-width pattern prunes the backtracking tree at the current point when\nbacktracked into on failure. Consider the pattern \"/A (*PRUNE) B/\", where A and B are\ncomplex patterns. Until the \"(*PRUNE)\" verb is reached, A may backtrack as necessary\nto match. Once it is reached, matching continues in B, which may also backtrack as\nnecessary; however, should B not match, then no further backtracking will take place,\nand the pattern will fail outright at the current starting position.\n\nThe following example counts all the possible matching strings in a pattern (without\nactually matching any of them).\n\n'aaab' =~ /a+b?(?{print \"$&\\n\"; $count++})(*FAIL)/;\nprint \"Count=$count\\n\";\n\nwhich produces:\n\naaab\naaa\naa\na\naab\naa\na\nab\na\nCount=9\n\nIf we add a \"(*PRUNE)\" before the count like the following\n\n'aaab' =~ /a+b?(*PRUNE)(?{print \"$&\\n\"; $count++})(*FAIL)/;\nprint \"Count=$count\\n\";\n\nwe prevent backtracking and find the count of the longest matching string at each\nmatching starting point like so:\n\naaab\naab\nab\nCount=3\n\nAny number of \"(*PRUNE)\" assertions may be used in a pattern.\n\nSee also \"(?>pattern)\" and possessive quantifiers for other ways to control\nbacktracking. In some cases, the use of \"(*PRUNE)\" can be replaced with a\n\"(?>pattern)\" with no functional difference; however, \"(*PRUNE)\" can be used to handle\ncases that cannot be expressed using a \"(?>pattern)\" alone.\n\n\"(*SKIP)\" \"(*SKIP:NAME)\"\nThis zero-width pattern is similar to \"(*PRUNE)\", except that on failure it also\nsignifies that whatever text that was matched leading up to the \"(*SKIP)\" pattern\nbeing executed cannot be part of any match of this pattern. This effectively means\nthat the regex engine \"skips\" forward to this position on failure and tries to match\nagain, (assuming that there is sufficient room to match).\n\nThe name of the \"(*SKIP:NAME)\" pattern has special significance. If a \"(*MARK:NAME)\"\nwas encountered while matching, then it is that position which is used as the \"skip\npoint\". If no \"(*MARK)\" of that name was encountered, then the \"(*SKIP)\" operator has\nno effect. When used without a name the \"skip point\" is where the match point was when\nexecuting the \"(*SKIP)\" pattern.\n\nCompare the following to the examples in \"(*PRUNE)\"; note the string is twice as long:\n\n'aaabaaab' =~ /a+b?(*SKIP)(?{print \"$&\\n\"; $count++})(*FAIL)/;\nprint \"Count=$count\\n\";\n\noutputs\n\naaab\naaab\nCount=2\n\nOnce the 'aaab' at the start of the string has matched, and the \"(*SKIP)\" executed,\nthe next starting point will be where the cursor was when the \"(*SKIP)\" was executed.\n\n\"(*MARK:NAME)\" \"(*:NAME)\"\nThis zero-width pattern can be used to mark the point reached in a string when a\ncertain part of the pattern has been successfully matched. This mark may be given a\nname. A later \"(*SKIP)\" pattern will then skip forward to that point if backtracked\ninto on failure. Any number of \"(*MARK)\" patterns are allowed, and the NAME portion\nmay be duplicated.\n\nIn addition to interacting with the \"(*SKIP)\" pattern, \"(*MARK:NAME)\" can be used to\n\"label\" a pattern branch, so that after matching, the program can determine which\nbranches of the pattern were involved in the match.\n\nWhen a match is successful, the $REGMARK variable will be set to the name of the most\nrecently executed \"(*MARK:NAME)\" that was involved in the match.\n\nThis can be used to determine which branch of a pattern was matched without using a\nseparate capture group for each branch, which in turn can result in a performance\nimprovement, as perl cannot optimize \"/(?:(x)|(y)|(z))/\" as efficiently as something\nlike \"/(?:x(*MARK:x)|y(*MARK:y)|z(*MARK:z))/\".\n\nWhen a match has failed, and unless another verb has been involved in failing the\nmatch and has provided its own name to use, the $REGERROR variable will be set to the\nname of the most recently executed \"(*MARK:NAME)\".\n\nSee \"(*SKIP)\" for more details.\n\nAs a shortcut \"(*MARK:NAME)\" can be written \"(*:NAME)\".\n\n\"(*THEN)\" \"(*THEN:NAME)\"\nThis is similar to the \"cut group\" operator \"::\" from Raku.  Like \"(*PRUNE)\", this\nverb always matches, and when backtracked into on failure, it causes the regex engine\nto try the next alternation in the innermost enclosing group (capturing or otherwise)\nthat has alternations.  The two branches of a \"(?(condition)yes-pattern|no-pattern)\"\ndo not count as an alternation, as far as \"(*THEN)\" is concerned.\n\nIts name comes from the observation that this operation combined with the alternation\noperator (\"|\") can be used to create what is essentially a pattern-based if/then/else\nblock:\n\n( COND (*THEN) FOO | COND2 (*THEN) BAR | COND3 (*THEN) BAZ )\n\nNote that if this operator is used and NOT inside of an alternation then it acts\nexactly like the \"(*PRUNE)\" operator.\n\n/ A (*PRUNE) B /\n\nis the same as\n\n/ A (*THEN) B /\n\nbut\n\n/ ( A (*THEN) B | C ) /\n\nis not the same as\n\n/ ( A (*PRUNE) B | C ) /\n\nas after matching the A but failing on the B the \"(*THEN)\" verb will backtrack and try\nC; but the \"(*PRUNE)\" verb will simply fail.\n\n\"(*COMMIT)\" \"(*COMMIT:arg)\"\nThis is the Raku \"commit pattern\" \"<commit>\" or \":::\". It's a zero-width pattern\nsimilar to \"(*SKIP)\", except that when backtracked into on failure it causes the match\nto fail outright. No further attempts to find a valid match by advancing the start\npointer will occur again.  For example,\n\n'aaabaaab' =~ /a+b?(*COMMIT)(?{print \"$&\\n\"; $count++})(*FAIL)/;\nprint \"Count=$count\\n\";\n\noutputs\n\naaab\nCount=1\n\nIn other words, once the \"(*COMMIT)\" has been entered, and if the pattern does not\nmatch, the regex engine will not try any further matching on the rest of the string.\n\n\"(*FAIL)\" \"(*F)\" \"(*FAIL:arg)\"\nThis pattern matches nothing and always fails. It can be used to force the engine to\nbacktrack. It is equivalent to \"(?!)\", but easier to read. In fact, \"(?!)\" gets\noptimised into \"(*FAIL)\" internally. You can provide an argument so that if the match\nfails because of this \"FAIL\" directive the argument can be obtained from $REGERROR.\n\nIt is probably useful only when combined with \"(?{})\" or \"(??{})\".\n\n\"(*ACCEPT)\" \"(*ACCEPT:arg)\"\nThis pattern matches nothing and causes the end of successful matching at the point at\nwhich the \"(*ACCEPT)\" pattern was encountered, regardless of whether there is actually\nmore to match in the string. When inside of a nested pattern, such as recursion, or in\na subpattern dynamically generated via \"(??{})\", only the innermost pattern is ended\nimmediately.\n\nIf the \"(*ACCEPT)\" is inside of capturing groups then the groups are marked as ended\nat the point at which the \"(*ACCEPT)\" was encountered.  For instance:\n\n'AB' =~ /(A (A|B(*ACCEPT)|C) D)(E)/x;\n\nwill match, and $1 will be \"AB\" and $2 will be \"B\", $3 will not be set. If another\nbranch in the inner parentheses was matched, such as in the string 'ACDE', then the\n\"D\" and \"E\" would have to be matched as well.\n\nYou can provide an argument, which will be available in the var $REGMARK after the\nmatch completes.\n"
                    },
                    {
                        "name": "Warning on \"\\1\" Instead of $1",
                        "content": "Some people get too used to writing things like:\n\n$pattern =~ s/(\\W)/\\\\\\1/g;\n\nThis is grandfathered (for \\1 to \\9) for the RHS of a substitute to avoid shocking the sed\naddicts, but it's a dirty habit to get into.  That's because in PerlThink, the righthand side\nof an \"s///\" is a double-quoted string.  \"\\1\" in the usual double-quoted string means a\ncontrol-A.  The customary Unix meaning of \"\\1\" is kludged in for \"s///\".  However, if you get\ninto the habit of doing that, you get yourself into trouble if you then add an \"/e\" modifier.\n\ns/(\\d+)/ \\1 + 1 /eg;            # causes warning under -w\n\nOr if you try to do\n\ns/(\\d+)/\\1000/;\n\nYou can't disambiguate that by saying \"\\{1}000\", whereas you can fix it with \"${1}000\".  The\noperation of interpolation should not be confused with the operation of matching a\nbackreference.  Certainly they mean two different things on the left side of the \"s///\".\n"
                    },
                    {
                        "name": "Repeated Patterns Matching a Zero-length Substring",
                        "content": "WARNING: Difficult material (and prose) ahead.  This section needs a rewrite.\n\nRegular expressions provide a terse and powerful programming language.  As with most other\npower tools, power comes together with the ability to wreak havoc.\n\nA common abuse of this power stems from the ability to make infinite loops using regular\nexpressions, with something as innocuous as:\n\n'foo' =~ m{ ( o? )* }x;\n\nThe \"o?\" matches at the beginning of \"\"foo\"\", and since the position in the string is not\nmoved by the match, \"o?\" would match again and again because of the \"*\" quantifier.  Another\ncommon way to create a similar cycle is with the looping modifier \"/g\":\n\n@matches = ( 'foo' =~ m{ o? }xg );\n\nor\n\nprint \"match: <$&>\\n\" while 'foo' =~ m{ o? }xg;\n\nor the loop implied by \"split()\".\n\nHowever, long experience has shown that many programming tasks may be significantly\nsimplified by using repeated subexpressions that may match zero-length substrings.  Here's a\nsimple example being:\n\n@chars = split //, $string;           # // is not magic in split\n($whitewashed = $string) =~ s/()/ /g; # parens avoid magic s// /\n\nThus Perl allows such constructs, by forcefully breaking the infinite loop.  The rules for\nthis are different for lower-level loops given by the greedy quantifiers \"*+{}\", and for\nhigher-level ones like the \"/g\" modifier or \"split()\" operator.\n\nThe lower-level loops are interrupted (that is, the loop is broken) when Perl detects that a\nrepeated expression matched a zero-length substring.   Thus\n\nm{ (?: NONZEROLENGTH | ZEROLENGTH )* }x;\n\nis made equivalent to\n\nm{ (?: NONZEROLENGTH )* (?: ZEROLENGTH )? }x;\n\nFor example, this program\n\n#!perl -l\n\"aaaaab\" =~ /\n(?:\na                 # non-zero\n|                 # or\n(?{print \"hello\"}) # print hello whenever this\n#    branch is tried\n(?=(b))            # zero-width assertion\n)*  # any number of times\n/x;\nprint $&;\nprint $1;\n\nprints\n\nhello\naaaaa\nb\n\nNotice that \"hello\" is only printed once, as when Perl sees that the sixth iteration of the\noutermost \"(?:)*\" matches a zero-length string, it stops the \"*\".\n\nThe higher-level loops preserve an additional state between iterations: whether the last\nmatch was zero-length.  To break the loop, the following match after a zero-length match is\nprohibited to have a length of zero.  This prohibition interacts with backtracking (see\n\"Backtracking\"), and so the second best match is chosen if the best match is of zero length.\n\nFor example:\n\n$ = 'bar';\ns/\\w??/<$&>/g;\n\nresults in \"<><b><><a><><r><>\".  At each position of the string the best match given by non-\ngreedy \"??\" is the zero-length match, and the second best match is what is matched by \"\\w\".\nThus zero-length matches alternate with one-character-long matches.\n\nSimilarly, for repeated \"m/()/g\" the second-best match is the match at the position one notch\nfurther in the string.\n\nThe additional state of being matched with zero-length is associated with the matched string,\nand is reset by each assignment to \"pos()\".  Zero-length matches at the end of the previous\nmatch are ignored during \"split\".\n"
                    },
                    {
                        "name": "Combining RE Pieces",
                        "content": "Each of the elementary pieces of regular expressions which were described before (such as\n\"ab\" or \"\\Z\") could match at most one substring at the given position of the input string.\nHowever, in a typical regular expression these elementary pieces are combined into more\ncomplicated patterns using combining operators \"ST\", \"S|T\", \"S*\" etc.  (in these examples \"S\"\nand \"T\" are regular subexpressions).\n\nSuch combinations can include alternatives, leading to a problem of choice: if we match a\nregular expression \"a|ab\" against \"abc\", will it match substring \"a\" or \"ab\"?  One way to\ndescribe which substring is actually matched is the concept of backtracking (see\n\"Backtracking\").  However, this description is too low-level and makes you think in terms of\na particular implementation.\n\nAnother description starts with notions of \"better\"/\"worse\".  All the substrings which may be\nmatched by the given regular expression can be sorted from the \"best\" match to the \"worst\"\nmatch, and it is the \"best\" match which is chosen.  This substitutes the question of \"what is\nchosen?\"  by the question of \"which matches are better, and which are worse?\".\n\nAgain, for elementary pieces there is no such question, since at most one match at a given\nposition is possible.  This section describes the notion of better/worse for combining\noperators.  In the description below \"S\" and \"T\" are regular subexpressions.\n\n\"ST\"\nConsider two possible matches, \"AB\" and \"A'B'\", \"A\" and \"A'\" are substrings which can be\nmatched by \"S\", \"B\" and \"B'\" are substrings which can be matched by \"T\".\n\nIf \"A\" is a better match for \"S\" than \"A'\", \"AB\" is a better match than \"A'B'\".\n\nIf \"A\" and \"A'\" coincide: \"AB\" is a better match than \"AB'\" if \"B\" is a better match for\n\"T\" than \"B'\".\n\n\"S|T\"\nWhen \"S\" can match, it is a better match than when only \"T\" can match.\n\nOrdering of two matches for \"S\" is the same as for \"S\".  Similar for two matches for \"T\".\n\n\"S{REPEATCOUNT}\"\nMatches as \"SSS...S\" (repeated as many times as necessary).\n\n\"S{min,max}\"\nMatches as \"S{max}|S{max-1}|...|S{min+1}|S{min}\".\n\n\"S{min,max}?\"\nMatches as \"S{min}|S{min+1}|...|S{max-1}|S{max}\".\n\n\"S?\", \"S*\", \"S+\"\nSame as \"S{0,1}\", \"S{0,BIGNUMBER}\", \"S{1,BIGNUMBER}\" respectively.\n\n\"S??\", \"S*?\", \"S+?\"\nSame as \"S{0,1}?\", \"S{0,BIGNUMBER}?\", \"S{1,BIGNUMBER}?\" respectively.\n\n\"(?>S)\"\nMatches the best match for \"S\" and only that.\n\n\"(?=S)\", \"(?<=S)\"\nOnly the best match for \"S\" is considered.  (This is important only if \"S\" has capturing\nparentheses, and backreferences are used somewhere else in the whole regular expression.)\n\n\"(?!S)\", \"(?<!S)\"\nFor this grouping operator there is no need to describe the ordering, since only whether\nor not \"S\" can match is important.\n\n\"(??{ EXPR })\", \"(?PARNO)\"\nThe ordering is the same as for the regular expression which is the result of EXPR, or\nthe pattern contained by capture group PARNO.\n\n\"(?(condition)yes-pattern|no-pattern)\"\nRecall that which of yes-pattern or no-pattern actually matches is already determined.\nThe ordering of the matches is the same as for the chosen subexpression.\n\nThe above recipes describe the ordering of matches at a given position.  One more rule is\nneeded to understand how a match is determined for the whole regular expression: a match at\nan earlier position is always better than a match at a later position.\n"
                    },
                    {
                        "name": "Creating Custom RE Engines",
                        "content": "As of Perl 5.10.0, one can create custom regular expression engines.  This is not for the\nfaint of heart, as they have to plug in at the C level.  See perlreapi for more details.\n\nAs an alternative, overloaded constants (see overload) provide a simple way to extend the\nfunctionality of the RE engine, by substituting one pattern for another.\n\nSuppose that we want to enable a new RE escape-sequence \"\\Y|\" which matches at a boundary\nbetween whitespace characters and non-whitespace characters.  Note that\n\"(?=\\S)(?<!\\S)|(?!\\S)(?<=\\S)\" matches exactly at these positions, so we want to have each\n\"\\Y|\" in the place of the more complicated version.  We can create a module \"customre\" to do\nthis:\n\npackage customre;\nuse overload;\n\nsub import {\nshift;\ndie \"No argument to customre::import allowed\" if @;\noverload::constant 'qr' => \\&convert;\n}\n\nsub invalid { die \"/$[0]/: invalid escape '\\\\$[1]'\"}\n\n# We must also take care of not escaping the legitimate \\\\Y|\n# sequence, hence the presence of '\\\\' in the conversion rules.\nmy %rules = ( '\\\\' => '\\\\\\\\',\n'Y|' => qr/(?=\\S)(?<!\\S)|(?!\\S)(?<=\\S)/ );\nsub convert {\nmy $re = shift;\n$re =~ s{\n\\\\ ( \\\\ | Y . )\n}\n{ $rules{$1} or invalid($re,$1) }sgex;\nreturn $re;\n}\n\nNow \"use customre\" enables the new escape in constant regular expressions, i.e., those\nwithout any runtime variable interpolations.  As documented in overload, this conversion will\nwork only over literal parts of regular expressions.  For \"\\Y|$re\\Y|\" the variable part of\nthis regular expression needs to be converted explicitly (but only if the special meaning of\n\"\\Y|\" should be enabled inside $re):\n\nuse customre;\n$re = <>;\nchomp $re;\n$re = customre::convert $re;\n/\\Y|$re\\Y|/;\n"
                    },
                    {
                        "name": "Embedded Code Execution Frequency",
                        "content": "The exact rules for how often \"(??{})\" and \"(?{})\" are executed in a pattern are unspecified.\nIn the case of a successful match you can assume that they DWIM and will be executed in left\nto right order the appropriate number of times in the accepting path of the pattern as would\nany other meta-pattern.  How non-accepting pathways and match failures affect the number of\ntimes a pattern is executed is specifically unspecified and may vary depending on what\noptimizations can be applied to the pattern and is likely to change from version to version.\n\nFor instance in\n\n\"aaabcdeeeee\"=~/a(?{print \"a\"})b(?{print \"b\"})cde/;\n\nthe exact number of times \"a\" or \"b\" are printed out is unspecified for failure, but you may\nassume they will be printed at least once during a successful match, additionally you may\nassume that if \"b\" is printed, it will be preceded by at least one \"a\".\n\nIn the case of branching constructs like the following:\n\n/a(b|(?{ print \"a\" }))c(?{ print \"c\" })/;\n\nyou can assume that the input \"ac\" will output \"ac\", and that \"abc\" will output only \"c\".\n\nWhen embedded code is quantified, successful matches will call the code once for each matched\niteration of the quantifier.  For example:\n\n\"good\" =~ /g(?:o(?{print \"o\"}))*d/;\n\nwill output \"o\" twice.\n"
                    },
                    {
                        "name": "PCRE/Python Support",
                        "content": "As of Perl 5.10.0, Perl supports several Python/PCRE-specific extensions to the regex syntax.\nWhile Perl programmers are encouraged to use the Perl-specific syntax, the following are also\naccepted:\n\n\"(?P<NAME>pattern)\"\nDefine a named capture group. Equivalent to \"(?<NAME>pattern)\".\n\n\"(?P=NAME)\"\nBackreference to a named capture group. Equivalent to \"\\g{NAME}\".\n\n\"(?P>NAME)\"\nSubroutine call to a named capture group. Equivalent to \"(?&NAME)\".\n"
                    }
                ]
            },
            "BUGS": {
                "content": "There are a number of issues with regard to case-insensitive matching in Unicode rules.  See\n\"i\" under \"Modifiers\" above.\n\nThis document varies from difficult to understand to completely and utterly opaque.  The\nwandering prose riddled with jargon is hard to fathom in several places.\n\nThis document needs a rewrite that separates the tutorial content from the reference content.\n",
                "subsections": []
            },
            "SEE ALSO": {
                "content": "The syntax of patterns used in Perl pattern matching evolved from those supplied in the Bell\nLabs Research Unix 8th Edition (Version 8) regex routines.  (The code is actually derived\n(distantly) from Henry Spencer's freely redistributable reimplementation of those V8\nroutines.)\n\nperlrequick.\n\nperlretut.\n\n\"Regexp Quote-Like Operators\" in perlop.\n\n\"Gory details of parsing quoted constructs\" in perlop.\n\nperlfaq6.\n\n\"pos\" in perlfunc.\n\nperllocale.\n\nperlebcdic.\n\nMastering Regular Expressions by Jeffrey Friedl, published by O'Reilly and Associates.\n\n\n\nperl v5.34.0                                 2025-07-25                                    PERLRE(1)",
                "subsections": []
            }
        }
    }
}