{
    "content": [
        {
            "type": "text",
            "text": "# perlretut (man)\n\n## NAME\n\nperlretut - Perl regular expressions tutorial\n\n## DESCRIPTION\n\nThis page provides a basic tutorial on understanding, creating and using regular expressions\nin Perl.  It serves as a complement to the reference page on regular expressions perlre.\nRegular expressions are an integral part of the \"m//\", \"s///\", \"qr//\" and \"split\" operators\nand so this tutorial also overlaps with \"Regexp Quote-Like Operators\" in perlop and \"split\"\nin perlfunc.\n\n## Sections\n\n- **NAME**\n- **DESCRIPTION** (29 subsections)\n- **SEE ALSO**\n- **AUTHOR AND COPYRIGHT** (1 subsections)\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "perlretut",
        "section": "",
        "mode": "man",
        "summary": "perlretut - Perl regular expressions tutorial",
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 57,
                "subsections": [
                    {
                        "name": "Part 1: The basics",
                        "lines": 1
                    },
                    {
                        "name": "Simple word matching",
                        "lines": 215
                    },
                    {
                        "name": "Using character classes",
                        "lines": 209
                    },
                    {
                        "name": "Matching this or that",
                        "lines": 28
                    },
                    {
                        "name": "Grouping things and hierarchical matching",
                        "lines": 93
                    },
                    {
                        "name": "Extracting matches",
                        "lines": 33
                    },
                    {
                        "name": "Backreferences",
                        "lines": 27
                    },
                    {
                        "name": "Relative backreferences",
                        "lines": 30
                    },
                    {
                        "name": "Named backreferences",
                        "lines": 23
                    },
                    {
                        "name": "Alternative capture group numbering",
                        "lines": 21
                    },
                    {
                        "name": "Position information",
                        "lines": 46
                    },
                    {
                        "name": "Non-capturing groupings",
                        "lines": 32
                    },
                    {
                        "name": "Matching repetitions",
                        "lines": 262
                    },
                    {
                        "name": "Possessive quantifiers",
                        "lines": 39
                    },
                    {
                        "name": "Building a regexp",
                        "lines": 137
                    },
                    {
                        "name": "Using regular expressions in Perl",
                        "lines": 278
                    },
                    {
                        "name": "Part 2: Power tools",
                        "lines": 10
                    },
                    {
                        "name": "More on characters, strings, and character classes",
                        "lines": 172
                    },
                    {
                        "name": "Compiling and saving regular expressions",
                        "lines": 50
                    },
                    {
                        "name": "Composing regular expressions at runtime",
                        "lines": 61
                    },
                    {
                        "name": "Embedding comments and modifiers in a regular expression",
                        "lines": 53
                    },
                    {
                        "name": "Looking ahead and looking behind",
                        "lines": 64
                    },
                    {
                        "name": "Using independent subexpressions to prevent backtracking",
                        "lines": 54
                    },
                    {
                        "name": "Conditional expressions",
                        "lines": 41
                    },
                    {
                        "name": "Defining named patterns",
                        "lines": 21
                    },
                    {
                        "name": "Recursive patterns",
                        "lines": 27
                    },
                    {
                        "name": "A bit of magic: executing Perl code in a regular expression",
                        "lines": 200
                    },
                    {
                        "name": "Backtracking control verbs",
                        "lines": 29
                    },
                    {
                        "name": "Pragmas and debugging",
                        "lines": 126
                    }
                ]
            },
            {
                "name": "SEE ALSO",
                "lines": 11,
                "subsections": []
            },
            {
                "name": "AUTHOR AND COPYRIGHT",
                "lines": 4,
                "subsections": [
                    {
                        "name": "Acknowledgments",
                        "lines": 9
                    }
                ]
            }
        ],
        "sections": {
            "NAME": {
                "content": "perlretut - Perl regular expressions tutorial\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "This page provides a basic tutorial on understanding, creating and using regular expressions\nin Perl.  It serves as a complement to the reference page on regular expressions perlre.\nRegular expressions are an integral part of the \"m//\", \"s///\", \"qr//\" and \"split\" operators\nand so this tutorial also overlaps with \"Regexp Quote-Like Operators\" in perlop and \"split\"\nin perlfunc.\n\nPerl is widely renowned for excellence in text processing, and regular expressions are one of\nthe big factors behind this fame.  Perl regular expressions display an efficiency and\nflexibility unknown in most other computer languages.  Mastering even the basics of regular\nexpressions will allow you to manipulate text with surprising ease.\n\nWhat is a regular expression?  At its most basic, a regular expression is a template that is\nused to determine if a string has certain characteristics.  The string is most often some\ntext, such as a line, sentence, web page, or even a whole book, but it doesn't have to be.\nIt could be binary data, for example.  Biologists often use Perl to look for patterns in long\nDNA sequences.\n\nSuppose we want to determine if the text in variable, $var contains the sequence of\ncharacters \"m u s h r o o m\" (blanks added for legibility).  We can write in Perl\n\n$var =~ m/mushroom/\n\nThe value of this expression will be TRUE if $var contains that sequence of characters\nanywhere within it, and FALSE otherwise.  The portion enclosed in '/' characters denotes the\ncharacteristic we are looking for.  We use the term pattern for it.  The process of looking\nto see if the pattern occurs in the string is called matching, and the \"=~\" operator along\nwith the \"m//\" tell Perl to try to match the pattern against the string.  Note that the\npattern is also a string, but a very special kind of one, as we will see.  Patterns are in\ncommon use these days; examples are the patterns typed into a search engine to find web pages\nand the patterns used to list files in a directory, e.g., \"\"ls *.txt\"\" or \"\"dir *.*\"\".  In\nPerl, the patterns described by regular expressions are used not only to search strings, but\nto also extract desired parts of strings, and to do search and replace operations.\n\nRegular expressions have the undeserved reputation of being abstract and difficult to\nunderstand.  This really stems simply because the notation used to express them tends to be\nterse and dense, and not because of inherent complexity.  We recommend using the \"/x\" regular\nexpression modifier (described below) along with plenty of white space to make them less\ndense, and easier to read.  Regular expressions are constructed using simple concepts like\nconditionals and loops and are no more difficult to understand than the corresponding \"if\"\nconditionals and \"while\" loops in the Perl language itself.\n\nThis tutorial flattens the learning curve by discussing regular expression concepts, along\nwith their notation, one at a time and with many examples.  The first part of the tutorial\nwill progress from the simplest word searches to the basic regular expression concepts.  If\nyou master the first part, you will have all the tools needed to solve about 98% of your\nneeds.  The second part of the tutorial is for those comfortable with the basics and hungry\nfor more power tools.  It discusses the more advanced regular expression operators and\nintroduces the latest cutting-edge innovations.\n\nA note: to save time, \"regular expression\" is often abbreviated as regexp or regex.  Regexp\nis a more natural abbreviation than regex, but is harder to pronounce.  The Perl pod\ndocumentation is evenly split on regexp vs regex; in Perl, there is more than one way to\nabbreviate it.  We'll use regexp in this tutorial.\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": "Part 1: The basics",
                        "content": ""
                    },
                    {
                        "name": "Simple word matching",
                        "content": "The simplest regexp is simply a word, or more generally, a string of characters.  A regexp\nconsisting of just a word matches any string that contains that word:\n\n\"Hello World\" =~ /World/;  # matches\n\nWhat is this Perl statement all about? \"Hello World\" is a simple double-quoted string.\n\"World\" is the regular expression and the \"//\" enclosing \"/World/\" tells Perl to search a\nstring for a match.  The operator \"=~\" associates the string with the regexp match and\nproduces a true value if the regexp matched, or false if the regexp did not match.  In our\ncase, \"World\" matches the second word in \"Hello World\", so the expression is true.\nExpressions like this are useful in conditionals:\n\nif (\"Hello World\" =~ /World/) {\nprint \"It matches\\n\";\n}\nelse {\nprint \"It doesn't match\\n\";\n}\n\nThere are useful variations on this theme.  The sense of the match can be reversed by using\nthe \"!~\" operator:\n\nif (\"Hello World\" !~ /World/) {\nprint \"It doesn't match\\n\";\n}\nelse {\nprint \"It matches\\n\";\n}\n\nThe literal string in the regexp can be replaced by a variable:\n\nmy $greeting = \"World\";\nif (\"Hello World\" =~ /$greeting/) {\nprint \"It matches\\n\";\n}\nelse {\nprint \"It doesn't match\\n\";\n}\n\nIf you're matching against the special default variable $, the \"$ =~\" part can be omitted:\n\n$ = \"Hello World\";\nif (/World/) {\nprint \"It matches\\n\";\n}\nelse {\nprint \"It doesn't match\\n\";\n}\n\nAnd finally, the \"//\" default delimiters for a match can be changed to arbitrary delimiters\nby putting an 'm' out front:\n\n\"Hello World\" =~ m!World!;   # matches, delimited by '!'\n\"Hello World\" =~ m{World};   # matches, note the paired '{}'\n\"/usr/bin/perl\" =~ m\"/perl\"; # matches after '/usr/bin',\n# '/' becomes an ordinary char\n\n\"/World/\", \"m!World!\", and \"m{World}\" all represent the same thing.  When, e.g., the quote\n('\"') is used as a delimiter, the forward slash '/' becomes an ordinary character and can be\nused in this regexp without trouble.\n\nLet's consider how different regexps would match \"Hello World\":\n\n\"Hello World\" =~ /world/;  # doesn't match\n\"Hello World\" =~ /o W/;    # matches\n\"Hello World\" =~ /oW/;     # doesn't match\n\"Hello World\" =~ /World /; # doesn't match\n\nThe first regexp \"world\" doesn't match because regexps are by default case-sensitive.  The\nsecond regexp matches because the substring 'o W' occurs in the string \"Hello World\".  The\nspace character ' ' is treated like any other character in a regexp and is needed to match in\nthis case.  The lack of a space character is the reason the third regexp 'oW' doesn't match.\nThe fourth regexp \"\"World \"\" doesn't match because there is a space at the end of the regexp,\nbut not at the end of the string.  The lesson here is that regexps must match a part of the\nstring exactly in order for the statement to be true.\n\nIf a regexp matches in more than one place in the string, Perl will always match at the\nearliest possible point in the string:\n\n\"Hello World\" =~ /o/;       # matches 'o' in 'Hello'\n\"That hat is red\" =~ /hat/; # matches 'hat' in 'That'\n\nWith respect to character matching, there are a few more points you need to know about.\nFirst of all, not all characters can be used \"as-is\" in a match.  Some characters, called\nmetacharacters, are generally reserved for use in regexp notation.  The metacharacters are\n\n{}[]()^$.|*+?-#\\\n\nThis list is not as definitive as it may appear (or be claimed to be in other documentation).\nFor example, \"#\" is a metacharacter only when the \"/x\" pattern modifier (described below) is\nused, and both \"}\" and \"]\" are metacharacters only when paired with opening \"{\" or \"[\"\nrespectively; other gotchas apply.\n\nThe significance of each of these will be explained in the rest of the tutorial, but for now,\nit is important only to know that a metacharacter can be matched as-is by putting a backslash\nbefore it:\n\n\"2+2=4\" =~ /2+2/;    # doesn't match, + is a metacharacter\n\"2+2=4\" =~ /2\\+2/;   # matches, \\+ is treated like an ordinary +\n\"The interval is [0,1).\" =~ /[0,1)./     # is a syntax error!\n\"The interval is [0,1).\" =~ /\\[0,1\\)\\./  # matches\n\"#!/usr/bin/perl\" =~ /#!\\/usr\\/bin\\/perl/;  # matches\n\nIn the last regexp, the forward slash '/' is also backslashed, because it is used to delimit\nthe regexp.  This can lead to LTS (leaning toothpick syndrome), however, and it is often more\nreadable to change delimiters.\n\n\"#!/usr/bin/perl\" =~ m!#\\!/usr/bin/perl!;  # easier to read\n\nThe backslash character '\\' is a metacharacter itself and needs to be backslashed:\n\n'C:\\WIN32' =~ /C:\\\\WIN/;   # matches\n\nIn situations where it doesn't make sense for a particular metacharacter to mean what it\nnormally does, it automatically loses its metacharacter-ness and becomes an ordinary\ncharacter that is to be matched literally.  For example, the '}' is a metacharacter only when\nit is the mate of a '{' metacharacter.  Otherwise it is treated as a literal RIGHT CURLY\nBRACKET.  This may lead to unexpected results.  \"use re 'strict'\" can catch some of these.\n\nIn addition to the metacharacters, there are some ASCII characters which don't have printable\ncharacter equivalents and are instead represented by escape sequences.  Common examples are\n\"\\t\" for a tab, \"\\n\" for a newline, \"\\r\" for a carriage return and \"\\a\" for a bell (or\nalert).  If your string is better thought of as a sequence of arbitrary bytes, the octal\nescape sequence, e.g., \"\\033\", or hexadecimal escape sequence, e.g., \"\\x1B\" may be a more\nnatural representation for your bytes.  Here are some examples of escapes:\n\n\"1000\\t2000\" =~ m(0\\t2)   # matches\n\"1000\\n2000\" =~ /0\\n20/   # matches\n\"1000\\t2000\" =~ /\\000\\t2/ # doesn't match, \"0\" ne \"\\000\"\n\"cat\"   =~ /\\o{143}\\x61\\x74/ # matches in ASCII, but a weird way\n# to spell cat\n\nIf you've been around Perl a while, all this talk of escape sequences may seem familiar.\nSimilar escape sequences are used in double-quoted strings and in fact the regexps in Perl\nare mostly treated as double-quoted strings.  This means that variables can be used in\nregexps as well.  Just like double-quoted strings, the values of the variables in the regexp\nwill be substituted in before the regexp is evaluated for matching purposes.  So we have:\n\n$foo = 'house';\n'housecat' =~ /$foo/;      # matches\n'cathouse' =~ /cat$foo/;   # matches\n'housecat' =~ /${foo}cat/; # matches\n\nSo far, so good.  With the knowledge above you can already perform searches with just about\nany literal string regexp you can dream up.  Here is a very simple emulation of the Unix grep\nprogram:\n\n% cat > simplegrep\n#!/usr/bin/perl\n$regexp = shift;\nwhile (<>) {\nprint if /$regexp/;\n}\n^D\n\n% chmod +x simplegrep\n\n% simplegrep abba /usr/dict/words\nBabbage\ncabbage\ncabbages\nsabbath\nSabbathize\nSabbathizes\nsabbatical\nscabbard\nscabbards\n\nThis program is easy to understand.  \"#!/usr/bin/perl\" is the standard way to invoke a perl\nprogram from the shell.  \"$regexp = shift;\" saves the first command line argument as the\nregexp to be used, leaving the rest of the command line arguments to be treated as files.\n\"while (<>)\" loops over all the lines in all the files.  For each line, \"print if /$regexp/;\"\nprints the line if the regexp matches the line.  In this line, both \"print\" and \"/$regexp/\"\nuse the default variable $ implicitly.\n\nWith all of the regexps above, if the regexp matched anywhere in the string, it was\nconsidered a match.  Sometimes, however, we'd like to specify where in the string the regexp\nshould try to match.  To do this, we would use the anchor metacharacters '^' and '$'.  The\nanchor '^' means match at the beginning of the string and the anchor '$' means match at the\nend of the string, or before a newline at the end of the string.  Here is how they are used:\n\n\"housekeeper\" =~ /keeper/;    # matches\n\"housekeeper\" =~ /^keeper/;   # doesn't match\n\"housekeeper\" =~ /keeper$/;   # matches\n\"housekeeper\\n\" =~ /keeper$/; # matches\n\nThe second regexp doesn't match because '^' constrains \"keeper\" to match only at the\nbeginning of the string, but \"housekeeper\" has keeper starting in the middle.  The third\nregexp does match, since the '$' constrains \"keeper\" to match only at the end of the string.\n\nWhen both '^' and '$' are used at the same time, the regexp has to match both the beginning\nand the end of the string, i.e., the regexp matches the whole string.  Consider\n\n\"keeper\" =~ /^keep$/;      # doesn't match\n\"keeper\" =~ /^keeper$/;    # matches\n\"\"       =~ /^$/;          # ^$ matches an empty string\n\nThe first regexp doesn't match because the string has more to it than \"keep\".  Since the\nsecond regexp is exactly the string, it matches.  Using both '^' and '$' in a regexp forces\nthe complete string to match, so it gives you complete control over which strings match and\nwhich don't.  Suppose you are looking for a fellow named bert, off in a string by himself:\n\n\"dogbert\" =~ /bert/;   # matches, but not what you want\n\n\"dilbert\" =~ /^bert/;  # doesn't match, but ..\n\"bertram\" =~ /^bert/;  # matches, so still not good enough\n\n\"bertram\" =~ /^bert$/; # doesn't match, good\n\"dilbert\" =~ /^bert$/; # doesn't match, good\n\"bert\"    =~ /^bert$/; # matches, perfect\n\nOf course, in the case of a literal string, one could just as easily use the string\ncomparison \"$string eq 'bert'\" and it would be more efficient.   The  \"^...$\" regexp really\nbecomes useful when we add in the more powerful regexp tools below.\n"
                    },
                    {
                        "name": "Using character classes",
                        "content": "Although one can already do quite a lot with the literal string regexps above, we've only\nscratched the surface of regular expression technology.  In this and subsequent sections we\nwill introduce regexp concepts (and associated metacharacter notations) that will allow a\nregexp to represent not just a single character sequence, but a whole class of them.\n\nOne such concept is that of a character class.  A character class allows a set of possible\ncharacters, rather than just a single character, to match at a particular point in a regexp.\nYou can define your own custom character classes.  These are denoted by brackets \"[...]\",\nwith the set of characters to be possibly matched inside.  Here are some examples:\n\n/cat/;       # matches 'cat'\n/[bcr]at/;   # matches 'bat, 'cat', or 'rat'\n/item[0123456789]/;  # matches 'item0' or ... or 'item9'\n\"abc\" =~ /[cab]/;    # matches 'a'\n\nIn the last statement, even though 'c' is the first character in the class, 'a' matches\nbecause the first character position in the string is the earliest point at which the regexp\ncan match.\n\n/[yY][eE][sS]/;      # match 'yes' in a case-insensitive way\n# 'yes', 'Yes', 'YES', etc.\n\nThis regexp displays a common task: perform a case-insensitive match.  Perl provides a way of\navoiding all those brackets by simply appending an 'i' to the end of the match.  Then\n\"/[yY][eE][sS]/;\" can be rewritten as \"/yes/i;\".  The 'i' stands for case-insensitive and is\nan example of a modifier of the matching operation.  We will meet other modifiers later in\nthe tutorial.\n\nWe saw in the section above that there were ordinary characters, which represented\nthemselves, and special characters, which needed a backslash '\\' to represent themselves.\nThe same is true in a character class, but the sets of ordinary and special characters inside\na character class are different than those outside a character class.  The special characters\nfor a character class are \"-]\\^$\" (and the pattern delimiter, whatever it is).  ']' is\nspecial because it denotes the end of a character class.  '$' is special because it denotes a\nscalar variable.  '\\' is special because it is used in escape sequences, just like above.\nHere is how the special characters \"]$\\\" are handled:\n\n/[\\]c]def/; # matches ']def' or 'cdef'\n$x = 'bcr';\n/[$x]at/;   # matches 'bat', 'cat', or 'rat'\n/[\\$x]at/;  # matches '$at' or 'xat'\n/[\\\\$x]at/; # matches '\\at', 'bat, 'cat', or 'rat'\n\nThe last two are a little tricky.  In \"[\\$x]\", the backslash protects the dollar sign, so the\ncharacter class has two members '$' and 'x'.  In \"[\\\\$x]\", the backslash is protected, so $x\nis treated as a variable and substituted in double quote fashion.\n\nThe special character '-' acts as a range operator within character classes, so that a\ncontiguous set of characters can be written as a range.  With ranges, the unwieldy\n\"[0123456789]\" and \"[abc...xyz]\" become the svelte \"[0-9]\" and \"[a-z]\".  Some examples are\n\n/item[0-9]/;  # matches 'item0' or ... or 'item9'\n/[0-9bx-z]aa/;  # matches '0aa', ..., '9aa',\n# 'baa', 'xaa', 'yaa', or 'zaa'\n/[0-9a-fA-F]/;  # matches a hexadecimal digit\n/[0-9a-zA-Z]/; # matches a \"word\" character,\n# like those in a Perl variable name\n\nIf '-' is the first or last character in a character class, it is treated as an ordinary\ncharacter; \"[-ab]\", \"[ab-]\" and \"[a\\-b]\" are all equivalent.\n\nThe special character '^' in the first position of a character class denotes a negated\ncharacter class, which matches any character but those in the brackets.  Both \"[...]\" and\n\"[^...]\" must match a character, or the match fails.  Then\n\n/[^a]at/;  # doesn't match 'aat' or 'at', but matches\n# all other 'bat', 'cat, '0at', '%at', etc.\n/[^0-9]/;  # matches a non-numeric character\n/[a^]at/;  # matches 'aat' or '^at'; here '^' is ordinary\n\nNow, even \"[0-9]\" can be a bother to write multiple times, so in the interest of saving\nkeystrokes and making regexps more readable, Perl has several abbreviations for common\ncharacter classes, as shown below.  Since the introduction of Unicode, unless the \"/a\"\nmodifier is in effect, these character classes match more than just a few characters in the\nASCII range.\n\n•   \"\\d\" matches a digit, not just \"[0-9]\" but also digits from non-roman scripts\n\n•   \"\\s\" matches a whitespace character, the set \"[\\ \\t\\r\\n\\f]\" and others\n\n•   \"\\w\" matches a word character (alphanumeric or ''), not just \"[0-9a-zA-Z]\" but also\ndigits and characters from non-roman scripts\n\n•   \"\\D\" is a negated \"\\d\"; it represents any other character than a digit, or \"[^\\d]\"\n\n•   \"\\S\" is a negated \"\\s\"; it represents any non-whitespace character \"[^\\s]\"\n\n•   \"\\W\" is a negated \"\\w\"; it represents any non-word character \"[^\\w]\"\n\n•   The period '.' matches any character but \"\\n\" (unless the modifier \"/s\" is in effect, as\nexplained below).\n\n•   \"\\N\", like the period, matches any character but \"\\n\", but it does so regardless of\nwhether the modifier \"/s\" is in effect.\n\nThe \"/a\" modifier, available starting in Perl 5.14,  is used to restrict the matches of \"\\d\",\n\"\\s\", and \"\\w\" to just those in the ASCII range.  It is useful to keep your program from\nbeing needlessly exposed to full Unicode (and its accompanying security considerations) when\nall you want is to process English-like text.  (The \"a\" may be doubled, \"/aa\", to provide\neven more restrictions, preventing case-insensitive matching of ASCII with non-ASCII\ncharacters; otherwise a Unicode \"Kelvin Sign\" would caselessly match a \"k\" or \"K\".)\n\nThe \"\\d\\s\\w\\D\\S\\W\" abbreviations can be used both inside and outside of bracketed character\nclasses.  Here are some in use:\n\n/\\d\\d:\\d\\d:\\d\\d/; # matches a hh:mm:ss time format\n/[\\d\\s]/;         # matches any digit or whitespace character\n/\\w\\W\\w/;         # matches a word char, followed by a\n# non-word char, followed by a word char\n/..rt/;           # matches any two chars, followed by 'rt'\n/end\\./;          # matches 'end.'\n/end[.]/;         # same thing, matches 'end.'\n\nBecause a period is a metacharacter, it needs to be escaped to match as an ordinary period.\nBecause, for example, \"\\d\" and \"\\w\" are sets of characters, it is incorrect to think of\n\"[^\\d\\w]\" as \"[\\D\\W]\"; in fact \"[^\\d\\w]\" is the same as \"[^\\w]\", which is the same as \"[\\W]\".\nThink DeMorgan's laws.\n\nIn actuality, the period and \"\\d\\s\\w\\D\\S\\W\" abbreviations are themselves types of character\nclasses, so the ones surrounded by brackets are just one type of character class.  When we\nneed to make a distinction, we refer to them as \"bracketed character classes.\"\n\nAn anchor useful in basic regexps is the word anchor \"\\b\".  This matches a boundary between a\nword character and a non-word character \"\\w\\W\" or \"\\W\\w\":\n\n$x = \"Housecat catenates house and cat\";\n$x =~ /cat/;    # matches cat in 'housecat'\n$x =~ /\\bcat/;  # matches cat in 'catenates'\n$x =~ /cat\\b/;  # matches cat in 'housecat'\n$x =~ /\\bcat\\b/;  # matches 'cat' at end of string\n\nNote in the last example, the end of the string is considered a word boundary.\n\nFor natural language processing (so that, for example, apostrophes are included in words),\nuse instead \"\\b{wb}\"\n\n\"don't\" =~ / .+? \\b{wb} /x;  # matches the whole string\n\nYou might wonder why '.' matches everything but \"\\n\" - why not every character? The reason is\nthat often one is matching against lines and would like to ignore the newline characters.\nFor instance, while the string \"\\n\" represents one line, we would like to think of it as\nempty.  Then\n\n\"\"   =~ /^$/;    # matches\n\"\\n\" =~ /^$/;    # matches, $ anchors before \"\\n\"\n\n\"\"   =~ /./;      # doesn't match; it needs a char\n\"\"   =~ /^.$/;    # doesn't match; it needs a char\n\"\\n\" =~ /^.$/;    # doesn't match; it needs a char other than \"\\n\"\n\"a\"  =~ /^.$/;    # matches\n\"a\\n\"  =~ /^.$/;  # matches, $ anchors before \"\\n\"\n\nThis behavior is convenient, because we usually want to ignore newlines when we count and\nmatch characters in a line.  Sometimes, however, we want to keep track of newlines.  We might\neven want '^' and '$' to anchor at the beginning and end of lines within the string, rather\nthan just the beginning and end of the string.  Perl allows us to choose between ignoring and\npaying attention to newlines by using the \"/s\" and \"/m\" modifiers.  \"/s\" and \"/m\" stand for\nsingle line and multi-line and they determine whether a string is to be treated as one\ncontinuous string, or as a set of lines.  The two modifiers affect two aspects of how the\nregexp is interpreted: 1) how the '.' character class is defined, and 2) where the anchors\n'^' and '$' are able to match.  Here are the four possible combinations:\n\n•   no modifiers: Default behavior.  '.' matches any character except \"\\n\".  '^' matches only\nat the beginning of the string and '$' matches only at the end or before a newline at the\nend.\n\n•   s modifier (\"/s\"): Treat string as a single long line.  '.' matches any character, even\n\"\\n\".  '^' matches only at the beginning of the string and '$' matches only at the end or\nbefore a newline at the end.\n\n•   m modifier (\"/m\"): Treat string as a set of multiple lines.  '.' matches any character\nexcept \"\\n\".  '^' and '$' are able to match at the start or end of any line within the\nstring.\n\n•   both s and m modifiers (\"/sm\"): Treat string as a single long line, but detect multiple\nlines.  '.' matches any character, even \"\\n\".  '^' and '$', however, are able to match at\nthe start or end of any line within the string.\n\nHere are examples of \"/s\" and \"/m\" in action:\n\n$x = \"There once was a girl\\nWho programmed in Perl\\n\";\n\n$x =~ /^Who/;   # doesn't match, \"Who\" not at start of string\n$x =~ /^Who/s;  # doesn't match, \"Who\" not at start of string\n$x =~ /^Who/m;  # matches, \"Who\" at start of second line\n$x =~ /^Who/sm; # matches, \"Who\" at start of second line\n\n$x =~ /girl.Who/;   # doesn't match, \".\" doesn't match \"\\n\"\n$x =~ /girl.Who/s;  # matches, \".\" matches \"\\n\"\n$x =~ /girl.Who/m;  # doesn't match, \".\" doesn't match \"\\n\"\n$x =~ /girl.Who/sm; # matches, \".\" matches \"\\n\"\n\nMost of the time, the default behavior is what is wanted, but \"/s\" and \"/m\" are occasionally\nvery useful.  If \"/m\" is being used, the start of the string can still be matched with \"\\A\"\nand the end of the string can still be matched with the anchors \"\\Z\" (matches both the end\nand the newline before, like '$'), and \"\\z\" (matches only the end):\n\n$x =~ /^Who/m;   # matches, \"Who\" at start of second line\n$x =~ /\\AWho/m;  # doesn't match, \"Who\" is not at start of string\n\n$x =~ /girl$/m;  # matches, \"girl\" at end of first line\n$x =~ /girl\\Z/m; # doesn't match, \"girl\" is not at end of string\n\n$x =~ /Perl\\Z/m; # matches, \"Perl\" is at newline before end\n$x =~ /Perl\\z/m; # doesn't match, \"Perl\" is not at end of string\n\nWe now know how to create choices among classes of characters in a regexp.  What about\nchoices among words or character strings? Such choices are described in the next section.\n"
                    },
                    {
                        "name": "Matching this or that",
                        "content": "Sometimes we would like our regexp to be able to match different possible words or character\nstrings.  This is accomplished by using the alternation metacharacter '|'.  To match \"dog\" or\n\"cat\", we form the regexp \"dog|cat\".  As before, Perl will try to match the regexp at the\nearliest possible point in the string.  At each character position, Perl will first try to\nmatch the first alternative, \"dog\".  If \"dog\" doesn't match, Perl will then try the next\nalternative, \"cat\".  If \"cat\" doesn't match either, then the match fails and Perl moves to\nthe next position in the string.  Some examples:\n\n\"cats and dogs\" =~ /cat|dog|bird/;  # matches \"cat\"\n\"cats and dogs\" =~ /dog|cat|bird/;  # matches \"cat\"\n\nEven though \"dog\" is the first alternative in the second regexp, \"cat\" is able to match\nearlier in the string.\n\n\"cats\"          =~ /c|ca|cat|cats/; # matches \"c\"\n\"cats\"          =~ /cats|cat|ca|c/; # matches \"cats\"\n\nHere, all the alternatives match at the first string position, so the first alternative is\nthe one that matches.  If some of the alternatives are truncations of the others, put the\nlongest ones first to give them a chance to match.\n\n\"cab\" =~ /a|b|c/ # matches \"c\"\n# /a|b|c/ == /[abc]/\n\nThe last example points out that character classes are like alternations of characters.  At a\ngiven character position, the first alternative that allows the regexp match to succeed will\nbe the one that matches.\n"
                    },
                    {
                        "name": "Grouping things and hierarchical matching",
                        "content": "Alternation allows a regexp to choose among alternatives, but by itself it is unsatisfying.\nThe reason is that each alternative is a whole regexp, but sometime we want alternatives for\njust part of a regexp.  For instance, suppose we want to search for housecats or\nhousekeepers.  The regexp \"housecat|housekeeper\" fits the bill, but is inefficient because we\nhad to type \"house\" twice.  It would be nice to have parts of the regexp be constant, like\n\"house\", and some parts have alternatives, like \"cat|keeper\".\n\nThe grouping metacharacters \"()\" solve this problem.  Grouping allows parts of a regexp to be\ntreated as a single unit.  Parts of a regexp are grouped by enclosing them in parentheses.\nThus we could solve the \"housecat|housekeeper\" by forming the regexp as \"house(cat|keeper)\".\nThe regexp \"house(cat|keeper)\" means match \"house\" followed by either \"cat\" or \"keeper\".\nSome more examples are\n\n/(a|b)b/;    # matches 'ab' or 'bb'\n/(ac|b)b/;   # matches 'acb' or 'bb'\n/(^a|b)c/;   # matches 'ac' at start of string or 'bc' anywhere\n/(a|[bc])d/; # matches 'ad', 'bd', or 'cd'\n\n/house(cat|)/;  # matches either 'housecat' or 'house'\n/house(cat(s|)|)/;  # matches either 'housecats' or 'housecat' or\n# 'house'.  Note groups can be nested.\n\n/(19|20|)\\d\\d/;  # match years 19xx, 20xx, or the Y2K problem, xx\n\"20\" =~ /(19|20|)\\d\\d/;  # matches the null alternative '()\\d\\d',\n# because '20\\d\\d' can't match\n\nAlternations behave the same way in groups as out of them: at a given string position, the\nleftmost alternative that allows the regexp to match is taken.  So in the last example at the\nfirst string position, \"20\" matches the second alternative, but there is nothing left over to\nmatch the next two digits \"\\d\\d\".  So Perl moves on to the next alternative, which is the\nnull alternative and that works, since \"20\" is two digits.\n\nThe process of trying one alternative, seeing if it matches, and moving on to the next\nalternative, while going back in the string from where the previous alternative was tried, if\nit doesn't, is called backtracking.  The term \"backtracking\" comes from the idea that\nmatching a regexp is like a walk in the woods.  Successfully matching a regexp is like\narriving at a destination.  There are many possible trailheads, one for each string position,\nand each one is tried in order, left to right.  From each trailhead there may be many paths,\nsome of which get you there, and some which are dead ends.  When you walk along a trail and\nhit a dead end, you have to backtrack along the trail to an earlier point to try another\ntrail.  If you hit your destination, you stop immediately and forget about trying all the\nother trails.  You are persistent, and only if you have tried all the trails from all the\ntrailheads and not arrived at your destination, do you declare failure.  To be concrete, here\nis a step-by-step analysis of what Perl does when it tries to match the regexp\n\n\"abcde\" =~ /(abd|abc)(df|d|de)/;\n\n0. Start with the first letter in the string 'a'.\n \n\n1. Try the first alternative in the first group 'abd'.\n \n\n2.  Match 'a' followed by 'b'. So far so good.\n \n\n3.  'd' in the regexp doesn't match 'c' in the string - a dead end.  So backtrack two\ncharacters and pick the second alternative in the first group 'abc'.\n \n\n4.  Match 'a' followed by 'b' followed by 'c'.  We are on a roll and have satisfied the first\ngroup. Set $1 to 'abc'.\n \n\n5 Move on to the second group and pick the first alternative 'df'.\n \n\n6 Match the 'd'.\n \n\n7.  'f' in the regexp doesn't match 'e' in the string, so a dead end.  Backtrack one\ncharacter and pick the second alternative in the second group 'd'.\n \n\n8.  'd' matches. The second grouping is satisfied, so set $2 to 'd'.\n \n\n9.  We are at the end of the regexp, so we are done! We have matched 'abcd' out of the string\n\"abcde\".\n\nThere are a couple of things to note about this analysis.  First, the third alternative in\nthe second group 'de' also allows a match, but we stopped before we got to it - at a given\ncharacter position, leftmost wins.  Second, we were able to get a match at the first\ncharacter position of the string 'a'.  If there were no matches at the first position, Perl\nwould move to the second character position 'b' and attempt the match all over again.  Only\nwhen all possible paths at all possible character positions have been exhausted does Perl\ngive up and declare \"$string =~ /(abd|abc)(df|d|de)/;\" to be false.\n\nEven with all this work, regexp matching happens remarkably fast.  To speed things up, Perl\ncompiles the regexp into a compact sequence of opcodes that can often fit inside a processor\ncache.  When the code is executed, these opcodes can then run at full throttle and search\nvery quickly.\n"
                    },
                    {
                        "name": "Extracting matches",
                        "content": "The grouping metacharacters \"()\" also serve another completely different function: they allow\nthe extraction of the parts of a string that matched.  This is very useful to find out what\nmatched and for text processing in general.  For each grouping, the part that matched inside\ngoes into the special variables $1, $2, etc.  They can be used just as ordinary variables:\n\n# extract hours, minutes, seconds\nif ($time =~ /(\\d\\d):(\\d\\d):(\\d\\d)/) {    # match hh:mm:ss format\n$hours = $1;\n$minutes = $2;\n$seconds = $3;\n}\n\nNow, we know that in scalar context, \"$time =~ /(\\d\\d):(\\d\\d):(\\d\\d)/\" returns a true or\nfalse value.  In list context, however, it returns the list of matched values \"($1,$2,$3)\".\nSo we could write the code more compactly as\n\n# extract hours, minutes, seconds\n($hours, $minutes, $second) = ($time =~ /(\\d\\d):(\\d\\d):(\\d\\d)/);\n\nIf the groupings in a regexp are nested, $1 gets the group with the leftmost opening\nparenthesis, $2 the next opening parenthesis, etc.  Here is a regexp with nested groups:\n\n/(ab(cd|ef)((gi)|j))/;\n1  2      34\n\nIf this regexp matches, $1 contains a string starting with 'ab', $2 is either set to 'cd' or\n'ef', $3 equals either 'gi' or 'j', and $4 is either set to 'gi', just like $3, or it remains\nundefined.\n\nFor convenience, Perl sets $+ to the string held by the highest numbered $1, $2,... that got\nassigned (and, somewhat related, $^N to the value of the $1, $2,... most-recently assigned;\ni.e. the $1, $2,... associated with the rightmost closing parenthesis used in the match).\n"
                    },
                    {
                        "name": "Backreferences",
                        "content": "Closely associated with the matching variables $1, $2, ... are the backreferences \"\\g1\",\n\"\\g2\",...  Backreferences are simply matching variables that can be used inside a regexp.\nThis is a really nice feature; what matches later in a regexp is made to depend on what\nmatched earlier in the regexp.  Suppose we wanted to look for doubled words in a text, like\n\"the the\".  The following regexp finds all 3-letter doubles with a space in between:\n\n/\\b(\\w\\w\\w)\\s\\g1\\b/;\n\nThe grouping assigns a value to \"\\g1\", so that the same 3-letter sequence is used for both\nparts.\n\nA similar task is to find words consisting of two identical parts:\n\n% simplegrep '^(\\w\\w\\w\\w|\\w\\w\\w|\\w\\w|\\w)\\g1$' /usr/dict/words\nberiberi\nbooboo\ncoco\nmama\nmurmur\npapa\n\nThe regexp has a single grouping which considers 4-letter combinations, then 3-letter\ncombinations, etc., and uses \"\\g1\" to look for a repeat.  Although $1 and \"\\g1\" represent the\nsame thing, care should be taken to use matched variables $1, $2,... only outside a regexp\nand backreferences \"\\g1\", \"\\g2\",... only inside a regexp; not doing so may lead to surprising\nand unsatisfactory results.\n"
                    },
                    {
                        "name": "Relative backreferences",
                        "content": "Counting the opening parentheses to get the correct number for a backreference is error-prone\nas soon as there is more than one capturing group.  A more convenient technique became\navailable with Perl 5.10: relative backreferences. To refer to the immediately preceding\ncapture group one now may write \"\\g-1\" or \"\\g{-1}\", the next but last is available via \"\\g-2\"\nor \"\\g{-2}\", and so on.\n\nAnother good reason in addition to readability and maintainability for using relative\nbackreferences is illustrated by the following example, where a simple pattern for matching\npeculiar strings is used:\n\n$a99a = '([a-z])(\\d)\\g2\\g1';   # matches a11a, g22g, x33x, etc.\n\nNow that we have this pattern stored as a handy string, we might feel tempted to use it as a\npart of some other pattern:\n\n$line = \"code=e99e\";\nif ($line =~ /^(\\w+)=$a99a$/){   # unexpected behavior!\nprint \"$1 is valid\\n\";\n} else {\nprint \"bad line: '$line'\\n\";\n}\n\nBut this doesn't match, at least not the way one might expect. Only after inserting the\ninterpolated $a99a and looking at the resulting full text of the regexp is it obvious that\nthe backreferences have backfired. The subexpression \"(\\w+)\" has snatched number 1 and\ndemoted the groups in $a99a by one rank. This can be avoided by using relative\nbackreferences:\n\n$a99a = '([a-z])(\\d)\\g{-1}\\g{-2}';  # safe for being interpolated\n"
                    },
                    {
                        "name": "Named backreferences",
                        "content": "Perl 5.10 also introduced named capture groups and named backreferences.  To attach a name to\na capturing group, you write either \"(?<name>...)\" or \"(?'name'...)\".  The backreference may\nthen be written as \"\\g{name}\".  It is permissible to attach the same name to more than one\ngroup, but then only the leftmost one of the eponymous set can be referenced.  Outside of the\npattern a named capture group is accessible through the \"%+\" hash.\n\nAssuming that we have to match calendar dates which may be given in one of the three formats\nyyyy-mm-dd, mm/dd/yyyy or dd.mm.yyyy, we can write three suitable patterns where we use 'd',\n'm' and 'y' respectively as the names of the groups capturing the pertaining components of a\ndate. The matching operation combines the three patterns as alternatives:\n\n$fmt1 = '(?<y>\\d\\d\\d\\d)-(?<m>\\d\\d)-(?<d>\\d\\d)';\n$fmt2 = '(?<m>\\d\\d)/(?<d>\\d\\d)/(?<y>\\d\\d\\d\\d)';\n$fmt3 = '(?<d>\\d\\d)\\.(?<m>\\d\\d)\\.(?<y>\\d\\d\\d\\d)';\nfor my $d (qw(2006-10-21 15.01.2007 10/31/2005)) {\nif ( $d =~ m{$fmt1|$fmt2|$fmt3} ){\nprint \"day=$+{d} month=$+{m} year=$+{y}\\n\";\n}\n}\n\nIf any of the alternatives matches, the hash \"%+\" is bound to contain the three key-value\npairs.\n"
                    },
                    {
                        "name": "Alternative capture group numbering",
                        "content": "Yet another capturing group numbering technique (also as from Perl 5.10) deals with the\nproblem of referring to groups within a set of alternatives.  Consider a pattern for matching\na time of the day, civil or military style:\n\nif ( $time =~ /(\\d\\d|\\d):(\\d\\d)|(\\d\\d)(\\d\\d)/ ){\n# process hour and minute\n}\n\nProcessing the results requires an additional if statement to determine whether $1 and $2 or\n$3 and $4 contain the goodies. It would be easier if we could use group numbers 1 and 2 in\nsecond alternative as well, and this is exactly what the parenthesized construct \"(?|...)\",\nset around an alternative achieves. Here is an extended version of the previous pattern:\n\nif($time =~ /(?|(\\d\\d|\\d):(\\d\\d)|(\\d\\d)(\\d\\d))\\s+([A-Z][A-Z][A-Z])/){\nprint \"hour=$1 minute=$2 zone=$3\\n\";\n}\n\nWithin the alternative numbering group, group numbers start at the same position for each\nalternative. After the group, numbering continues with one higher than the maximum reached\nacross all the alternatives.\n"
                    },
                    {
                        "name": "Position information",
                        "content": "In addition to what was matched, Perl also provides the positions of what was matched as\ncontents of the \"@-\" and \"@+\" arrays. \"$-[0]\" is the position of the start of the entire\nmatch and $+[0] is the position of the end. Similarly, \"$-[n]\" is the position of the start\nof the $n match and $+[n] is the position of the end. If $n is undefined, so are \"$-[n]\" and\n$+[n]. Then this code\n\n$x = \"Mmm...donut, thought Homer\";\n$x =~ /^(Mmm|Yech)\\.\\.\\.(donut|peas)/; # matches\nforeach $exp (1..$#-) {\nno strict 'refs';\nprint \"Match $exp: '$$exp' at position ($-[$exp],$+[$exp])\\n\";\n}\n\nprints\n\nMatch 1: 'Mmm' at position (0,3)\nMatch 2: 'donut' at position (6,11)\n\nEven if there are no groupings in a regexp, it is still possible to find out what exactly\nmatched in a string.  If you use them, Perl will set \"$`\" to the part of the string before\nthe match, will set $& to the part of the string that matched, and will set \"$'\" to the part\nof the string after the match.  An example:\n\n$x = \"the cat caught the mouse\";\n$x =~ /cat/;  # $` = 'the ', $& = 'cat', $' = ' caught the mouse'\n$x =~ /the/;  # $` = '', $& = 'the', $' = ' cat caught the mouse'\n\nIn the second match, \"$`\" equals '' because the regexp matched at the first character\nposition in the string and stopped; it never saw the second \"the\".\n\nIf your code is to run on Perl versions earlier than 5.20, it is worthwhile to note that\nusing \"$`\" and \"$'\" slows down regexp matching quite a bit, while $& slows it down to a\nlesser extent, because if they are used in one regexp in a program, they are generated for\nall regexps in the program.  So if raw performance is a goal of your application, they should\nbe avoided.  If you need to extract the corresponding substrings, use \"@-\" and \"@+\" instead:\n\n$` is the same as substr( $x, 0, $-[0] )\n$& is the same as substr( $x, $-[0], $+[0]-$-[0] )\n$' is the same as substr( $x, $+[0] )\n\nAs of Perl 5.10, the \"${^PREMATCH}\", \"${^MATCH}\" and \"${^POSTMATCH}\" variables may be used.\nThese are only set if the \"/p\" modifier is present.  Consequently they do not penalize the\nrest of the program.  In Perl 5.20, \"${^PREMATCH}\", \"${^MATCH}\" and \"${^POSTMATCH}\" are\navailable whether the \"/p\" has been used or not (the modifier is ignored), and \"$`\", \"$'\" and\n$& do not cause any speed difference.\n"
                    },
                    {
                        "name": "Non-capturing groupings",
                        "content": "A group that is required to bundle a set of alternatives may or may not be useful as a\ncapturing group.  If it isn't, it just creates a superfluous addition to the set of available\ncapture group values, inside as well as outside the regexp.  Non-capturing groupings, denoted\nby \"(?:regexp)\", still allow the regexp to be treated as a single unit, but don't establish a\ncapturing group at the same time.  Both capturing and non-capturing groupings are allowed to\nco-exist in the same regexp.  Because there is no extraction, non-capturing groupings are\nfaster than capturing groupings.  Non-capturing groupings are also handy for choosing exactly\nwhich parts of a regexp are to be extracted to matching variables:\n\n# match a number, $1-$4 are set, but we only want $1\n/([+-]?\\ *(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?)/;\n\n# match a number faster , only $1 is set\n/([+-]?\\ *(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?)/;\n\n# match a number, get $1 = whole number, $2 = exponent\n/([+-]?\\ *(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE]([+-]?\\d+))?)/;\n\nNon-capturing groupings are also useful for removing nuisance elements gathered from a split\noperation where parentheses are required for some reason:\n\n$x = '12aba34ba5';\n@num = split /(a|b)+/, $x;    # @num = ('12','a','34','a','5')\n@num = split /(?:a|b)+/, $x;  # @num = ('12','34','5')\n\nIn Perl 5.22 and later, all groups within a regexp can be set to non-capturing by using the\nnew \"/n\" flag:\n\n\"hello\" =~ /(hi|hello)/n; # $1 is not set!\n\nSee \"n\" in perlre for more information.\n"
                    },
                    {
                        "name": "Matching repetitions",
                        "content": "The examples in the previous section display an annoying weakness.  We were only matching\n3-letter words, or chunks of words of 4 letters or less.  We'd like to be able to match words\nor, more generally, strings of any length, without writing out tedious alternatives like\n\"\\w\\w\\w\\w|\\w\\w\\w|\\w\\w|\\w\".\n\nThis is exactly the problem the quantifier metacharacters '?', '*', '+', and \"{}\" were\ncreated for.  They allow us to delimit the number of repeats for a portion of a regexp we\nconsider to be a match.  Quantifiers are put immediately after the character, character\nclass, or grouping that we want to specify.  They have the following meanings:\n\n•   \"a?\" means: match 'a' 1 or 0 times\n\n•   \"a*\" means: match 'a' 0 or more times, i.e., any number of times\n\n•   \"a+\" means: match 'a' 1 or more times, i.e., at least once\n\n•   \"a{n,m}\" means: match at least \"n\" times, but not more than \"m\" times.\n\n•   \"a{n,}\" means: match at least \"n\" or more times\n\n•   \"a{,n}\" means: match at most \"n\" times, or fewer\n\n•   \"a{n}\" means: match exactly \"n\" times\n\nIf you like, you can add blanks (tab or space characters) within the braces, but adjacent to\nthem, and/or next to the comma (if any).\n\nHere are some examples:\n\n/[a-z]+\\s+\\d*/;  # match a lowercase word, at least one space, and\n# any number of digits\n/(\\w+)\\s+\\g1/;    # match doubled words of arbitrary length\n/y(es)?/i;       # matches 'y', 'Y', or a case-insensitive 'yes'\n$year =~ /^\\d{2,4}$/;  # make sure year is at least 2 but not more\n# than 4 digits\n$year =~ /^\\d{ 2, 4 }$/;    # Same; for those who like wide open\n# spaces.\n$year =~ /^\\d{2, 4}$/;      # Same.\n$year =~ /^\\d{4}$|^\\d{2}$/; # better match; throw out 3-digit dates\n$year =~ /^\\d{2}(\\d{2})?$/; # same thing written differently.\n# However, this captures the last two\n# digits in $1 and the other does not.\n\n% simplegrep '^(\\w+)\\g1$' /usr/dict/words   # isn't this easier?\nberiberi\nbooboo\ncoco\nmama\nmurmur\npapa\n\nFor all of these quantifiers, Perl will try to match as much of the string as possible, while\nstill allowing the regexp to succeed.  Thus with \"/a?.../\", Perl will first try to match the\nregexp with the 'a' present; if that fails, Perl will try to match the regexp without the 'a'\npresent.  For the quantifier '*', we get the following:\n\n$x = \"the cat in the hat\";\n$x =~ /^(.*)(cat)(.*)$/; # matches,\n# $1 = 'the '\n# $2 = 'cat'\n# $3 = ' in the hat'\n\nWhich is what we might expect, the match finds the only \"cat\" in the string and locks onto\nit.  Consider, however, this regexp:\n\n$x =~ /^(.*)(at)(.*)$/; # matches,\n# $1 = 'the cat in the h'\n# $2 = 'at'\n# $3 = ''   (0 characters match)\n\nOne might initially guess that Perl would find the \"at\" in \"cat\" and stop there, but that\nwouldn't give the longest possible string to the first quantifier \".*\".  Instead, the first\nquantifier \".*\" grabs as much of the string as possible while still having the regexp match.\nIn this example, that means having the \"at\" sequence with the final \"at\" in the string.  The\nother important principle illustrated here is that, when there are two or more elements in a\nregexp, the leftmost quantifier, if there is one, gets to grab as much of the string as\npossible, leaving the rest of the regexp to fight over scraps.  Thus in our example, the\nfirst quantifier \".*\" grabs most of the string, while the second quantifier \".*\" gets the\nempty string.   Quantifiers that grab as much of the string as possible are called maximal\nmatch or greedy quantifiers.\n\nWhen a regexp can match a string in several different ways, we can use the principles above\nto predict which way the regexp will match:\n\n•   Principle 0: Taken as a whole, any regexp will be matched at the earliest possible\nposition in the string.\n\n•   Principle 1: In an alternation \"a|b|c...\", the leftmost alternative that allows a match\nfor the whole regexp will be the one used.\n\n•   Principle 2: The maximal matching quantifiers '?', '*', '+' and \"{n,m}\" will in general\nmatch as much of the string as possible while still allowing the whole regexp to match.\n\n•   Principle 3: If there are two or more elements in a regexp, the leftmost greedy\nquantifier, if any, will match as much of the string as possible while still allowing the\nwhole regexp to match.  The next leftmost greedy quantifier, if any, will try to match as\nmuch of the string remaining available to it as possible, while still allowing the whole\nregexp to match.  And so on, until all the regexp elements are satisfied.\n\nAs we have seen above, Principle 0 overrides the others. The regexp will be matched as early\nas possible, with the other principles determining how the regexp matches at that earliest\ncharacter position.\n\nHere is an example of these principles in action:\n\n$x = \"The programming republic of Perl\";\n$x =~ /^(.+)(e|r)(.*)$/;  # matches,\n# $1 = 'The programming republic of Pe'\n# $2 = 'r'\n# $3 = 'l'\n\nThis regexp matches at the earliest string position, 'T'.  One might think that 'e', being\nleftmost in the alternation, would be matched, but 'r' produces the longest string in the\nfirst quantifier.\n\n$x =~ /(m{1,2})(.*)$/;  # matches,\n# $1 = 'mm'\n# $2 = 'ing republic of Perl'\n\nHere, The earliest possible match is at the first 'm' in \"programming\". \"m{1,2}\" is the first\nquantifier, so it gets to match a maximal \"mm\".\n\n$x =~ /.*(m{1,2})(.*)$/;  # matches,\n# $1 = 'm'\n# $2 = 'ing republic of Perl'\n\nHere, the regexp matches at the start of the string. The first quantifier \".*\" grabs as much\nas possible, leaving just a single 'm' for the second quantifier \"m{1,2}\".\n\n$x =~ /(.?)(m{1,2})(.*)$/;  # matches,\n# $1 = 'a'\n# $2 = 'mm'\n# $3 = 'ing republic of Perl'\n\nHere, \".?\" eats its maximal one character at the earliest possible position in the string,\n'a' in \"programming\", leaving \"m{1,2}\" the opportunity to match both 'm''s. Finally,\n\n\"aXXXb\" =~ /(X*)/; # matches with $1 = ''\n\nbecause it can match zero copies of 'X' at the beginning of the string.  If you definitely\nwant to match at least one 'X', use \"X+\", not \"X*\".\n\nSometimes greed is not good.  At times, we would like quantifiers to match a minimal piece of\nstring, rather than a maximal piece.  For this purpose, Larry Wall created the minimal match\nor non-greedy quantifiers \"??\", \"*?\", \"+?\", and \"{}?\".  These are the usual quantifiers with\na '?' appended to them.  They have the following meanings:\n\n•   \"a??\" means: match 'a' 0 or 1 times. Try 0 first, then 1.\n\n•   \"a*?\" means: match 'a' 0 or more times, i.e., any number of times, but as few times as\npossible\n\n•   \"a+?\" means: match 'a' 1 or more times, i.e., at least once, but as few times as possible\n\n•   \"a{n,m}?\" means: match at least \"n\" times, not more than \"m\" times, as few times as\npossible\n\n•   \"a{n,}?\" means: match at least \"n\" times, but as few times as possible\n\n•   \"a{,n}?\" means: match at most \"n\" times, but as few times as possible\n\n•   \"a{n}?\" means: match exactly \"n\" times.  Because we match exactly \"n\" times, \"a{n}?\" is\nequivalent to \"a{n}\" and is just there for notational consistency.\n\nLet's look at the example above, but with minimal quantifiers:\n\n$x = \"The programming republic of Perl\";\n$x =~ /^(.+?)(e|r)(.*)$/; # matches,\n# $1 = 'Th'\n# $2 = 'e'\n# $3 = ' programming republic of Perl'\n\nThe minimal string that will allow both the start of the string '^' and the alternation to\nmatch is \"Th\", with the alternation \"e|r\" matching 'e'.  The second quantifier \".*\" is free\nto gobble up the rest of the string.\n\n$x =~ /(m{1,2}?)(.*?)$/;  # matches,\n# $1 = 'm'\n# $2 = 'ming republic of Perl'\n\nThe first string position that this regexp can match is at the first 'm' in \"programming\". At\nthis position, the minimal \"m{1,2}?\"  matches just one 'm'.  Although the second quantifier\n\".*?\" would prefer to match no characters, it is constrained by the end-of-string anchor '$'\nto match the rest of the string.\n\n$x =~ /(.*?)(m{1,2}?)(.*)$/;  # matches,\n# $1 = 'The progra'\n# $2 = 'm'\n# $3 = 'ming republic of Perl'\n\nIn this regexp, you might expect the first minimal quantifier \".*?\"  to match the empty\nstring, because it is not constrained by a '^' anchor to match the beginning of the word.\nPrinciple 0 applies here, however.  Because it is possible for the whole regexp to match at\nthe start of the string, it will match at the start of the string.  Thus the first quantifier\nhas to match everything up to the first 'm'.  The second minimal quantifier matches just one\n'm' and the third quantifier matches the rest of the string.\n\n$x =~ /(.??)(m{1,2})(.*)$/;  # matches,\n# $1 = 'a'\n# $2 = 'mm'\n# $3 = 'ing republic of Perl'\n\nJust as in the previous regexp, the first quantifier \".??\" can match earliest at position\n'a', so it does.  The second quantifier is greedy, so it matches \"mm\", and the third matches\nthe rest of the string.\n\nWe can modify principle 3 above to take into account non-greedy quantifiers:\n\n•   Principle 3: If there are two or more elements in a regexp, the leftmost greedy (non-\ngreedy) quantifier, if any, will match as much (little) of the string as possible while\nstill allowing the whole regexp to match.  The next leftmost greedy (non-greedy)\nquantifier, if any, will try to match as much (little) of the string remaining available\nto it as possible, while still allowing the whole regexp to match.  And so on, until all\nthe regexp elements are satisfied.\n\nJust like alternation, quantifiers are also susceptible to backtracking.  Here is a step-by-\nstep analysis of the example\n\n$x = \"the cat in the hat\";\n$x =~ /^(.*)(at)(.*)$/; # matches,\n# $1 = 'the cat in the h'\n# $2 = 'at'\n# $3 = ''   (0 matches)\n\n0.  Start with the first letter in the string 't'.\n \n\n1.  The first quantifier '.*' starts out by matching the whole string \"\"the cat in the hat\"\".\n \n\n2.  'a' in the regexp element 'at' doesn't match the end of the string.  Backtrack one\ncharacter.\n \n\n3.  'a' in the regexp element 'at' still doesn't match the last letter of the string 't', so\nbacktrack one more character.\n \n\n4.  Now we can match the 'a' and the 't'.\n \n\n5.  Move on to the third element '.*'.  Since we are at the end of the string and '.*' can\nmatch 0 times, assign it the empty string.\n \n\n6.  We are done!\n\nMost of the time, all this moving forward and backtracking happens quickly and searching is\nfast. There are some pathological regexps, however, whose execution time exponentially grows\nwith the size of the string.  A typical structure that blows up in your face is of the form\n\n/(a|b+)*/;\n\nThe problem is the nested indeterminate quantifiers.  There are many different ways of\npartitioning a string of length n between the '+' and '*': one repetition with \"b+\" of length\nn, two repetitions with the first \"b+\" length k and the second with length n-k, m repetitions\nwhose bits add up to length n, etc.  In fact there are an exponential number of ways to\npartition a string as a function of its length.  A regexp may get lucky and match early in\nthe process, but if there is no match, Perl will try every possibility before giving up.  So\nbe careful with nested '*''s, \"{n,m}\"'s, and '+''s.  The book Mastering Regular Expressions\nby Jeffrey Friedl gives a wonderful discussion of this and other efficiency issues.\n"
                    },
                    {
                        "name": "Possessive quantifiers",
                        "content": "Backtracking during the relentless search for a match may be a waste of time, particularly\nwhen the match is bound to fail.  Consider the simple pattern\n\n/^\\w+\\s+\\w+$/; # a word, spaces, a word\n\nWhenever this is applied to a string which doesn't quite meet the pattern's expectations such\nas \"abc  \" or \"abc  def \", the regexp engine will backtrack, approximately once for each\ncharacter in the string.  But we know that there is no way around taking all of the initial\nword characters to match the first repetition, that all spaces must be eaten by the middle\npart, and the same goes for the second word.\n\nWith the introduction of the possessive quantifiers in Perl 5.10, we have a way of\ninstructing the regexp engine not to backtrack, with the usual quantifiers with a '+'\nappended to them.  This makes them greedy as well as stingy; once they succeed they won't\ngive anything back to permit another solution. They have the following meanings:\n\n•   \"a{n,m}+\" means: match at least \"n\" times, not more than \"m\" times, as many times as\npossible, and don't give anything up. \"a?+\" is short for \"a{0,1}+\"\n\n•   \"a{n,}+\" means: match at least \"n\" times, but as many times as possible, and don't give\nanything up. \"a++\" is short for \"a{1,}+\".\n\n•   \"a{,n}+\" means: match as many times as possible up to at most \"n\" times, and don't give\nanything up. \"a*+\" is short for \"a{0,}+\".\n\n•   \"a{n}+\" means: match exactly \"n\" times.  It is just there for notational consistency.\n\nThese possessive quantifiers represent a special case of a more general concept, the\nindependent subexpression, see below.\n\nAs an example where a possessive quantifier is suitable we consider matching a quoted string,\nas it appears in several programming languages.  The backslash is used as an escape character\nthat indicates that the next character is to be taken literally, as another character for the\nstring.  Therefore, after the opening quote, we expect a (possibly empty) sequence of\nalternatives: either some character except an unescaped quote or backslash or an escaped\ncharacter.\n\n/\"(?:[^\"\\\\]++|\\\\.)*+\"/;\n"
                    },
                    {
                        "name": "Building a regexp",
                        "content": "At this point, we have all the basic regexp concepts covered, so let's give a more involved\nexample of a regular expression.  We will build a regexp that matches numbers.\n\nThe first task in building a regexp is to decide what we want to match and what we want to\nexclude.  In our case, we want to match both integers and floating point numbers and we want\nto reject any string that isn't a number.\n\nThe next task is to break the problem down into smaller problems that are easily converted\ninto a regexp.\n\nThe simplest case is integers.  These consist of a sequence of digits, with an optional sign\nin front.  The digits we can represent with \"\\d+\" and the sign can be matched with \"[+-]\".\nThus the integer regexp is\n\n/[+-]?\\d+/;  # matches integers\n\nA floating point number potentially has a sign, an integral part, a decimal point, a\nfractional part, and an exponent.  One or more of these parts is optional, so we need to\ncheck out the different possibilities.  Floating point numbers which are in proper form\ninclude 123., 0.345, .34, -1e6, and 25.4E-72.  As with integers, the sign out front is\ncompletely optional and can be matched by \"[+-]?\".  We can see that if there is no exponent,\nfloating point numbers must have a decimal point, otherwise they are integers.  We might be\ntempted to model these with \"\\d*\\.\\d*\", but this would also match just a single decimal\npoint, which is not a number.  So the three cases of floating point number without exponent\nare\n\n/[+-]?\\d+\\./;  # 1., 321., etc.\n/[+-]?\\.\\d+/;  # .1, .234, etc.\n/[+-]?\\d+\\.\\d+/;  # 1.0, 30.56, etc.\n\nThese can be combined into a single regexp with a three-way alternation:\n\n/[+-]?(\\d+\\.\\d+|\\d+\\.|\\.\\d+)/;  # floating point, no exponent\n\nIn this alternation, it is important to put '\\d+\\.\\d+' before '\\d+\\.'.  If '\\d+\\.' were\nfirst, the regexp would happily match that and ignore the fractional part of the number.\n\nNow consider floating point numbers with exponents.  The key observation here is that both\nintegers and numbers with decimal points are allowed in front of an exponent.  Then\nexponents, like the overall sign, are independent of whether we are matching numbers with or\nwithout decimal points, and can be \"decoupled\" from the mantissa.  The overall form of the\nregexp now becomes clear:\n\n/^(optional sign)(integer | f.p. mantissa)(optional exponent)$/;\n\nThe exponent is an 'e' or 'E', followed by an integer.  So the exponent regexp is\n\n/[eE][+-]?\\d+/;  # exponent\n\nPutting all the parts together, we get a regexp that matches numbers:\n\n/^[+-]?(\\d+\\.\\d+|\\d+\\.|\\.\\d+|\\d+)([eE][+-]?\\d+)?$/;  # Ta da!\n\nLong regexps like this may impress your friends, but can be hard to decipher.  In complex\nsituations like this, the \"/x\" modifier for a match is invaluable.  It allows one to put\nnearly arbitrary whitespace and comments into a regexp without affecting their meaning.\nUsing it, we can rewrite our \"extended\" regexp in the more pleasing form\n\n/^\n[+-]?         # first, match an optional sign\n(             # then match integers or f.p. mantissas:\n\\d+\\.\\d+  # mantissa of the form a.b\n|\\d+\\.     # mantissa of the form a.\n|\\.\\d+     # mantissa of the form .b\n|\\d+       # integer of the form a\n)\n( [eE] [+-]? \\d+ )?  # finally, optionally match an exponent\n$/x;\n\nIf whitespace is mostly irrelevant, how does one include space characters in an extended\nregexp? The answer is to backslash it '\\ ' or put it in a character class \"[ ]\".  The same\nthing goes for pound signs: use \"\\#\" or \"[#]\".  For instance, Perl allows a space between the\nsign and the mantissa or integer, and we could add this to our regexp as follows:\n\n/^\n[+-]?\\ *      # first, match an optional sign *and space*\n(             # then match integers or f.p. mantissas:\n\\d+\\.\\d+  # mantissa of the form a.b\n|\\d+\\.     # mantissa of the form a.\n|\\.\\d+     # mantissa of the form .b\n|\\d+       # integer of the form a\n)\n( [eE] [+-]? \\d+ )?  # finally, optionally match an exponent\n$/x;\n\nIn this form, it is easier to see a way to simplify the alternation.  Alternatives 1, 2, and\n4 all start with \"\\d+\", so it could be factored out:\n\n/^\n[+-]?\\ *      # first, match an optional sign\n(             # then match integers or f.p. mantissas:\n\\d+       # start out with a ...\n(\n\\.\\d* # mantissa of the form a.b or a.\n)?        # ? takes care of integers of the form a\n|\\.\\d+     # mantissa of the form .b\n)\n( [eE] [+-]? \\d+ )?  # finally, optionally match an exponent\n$/x;\n\nStarting in Perl v5.26, specifying \"/xx\" changes the square-bracketed portions of a pattern\nto ignore tabs and space characters unless they are escaped by preceding them with a\nbackslash.  So, we could write\n\n/^\n[ + - ]?\\ *   # first, match an optional sign\n(             # then match integers or f.p. mantissas:\n\\d+       # start out with a ...\n(\n\\.\\d* # mantissa of the form a.b or a.\n)?        # ? takes care of integers of the form a\n|\\.\\d+     # mantissa of the form .b\n)\n( [ e E ] [ + - ]? \\d+ )?  # finally, optionally match an exponent\n$/xx;\n\nThis doesn't really improve the legibility of this example, but it's available in case you\nwant it.  Squashing the pattern down to the compact form, we have\n\n/^[+-]?\\ *(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?$/;\n\nThis is our final regexp.  To recap, we built a regexp by\n\n•   specifying the task in detail,\n\n•   breaking down the problem into smaller parts,\n\n•   translating the small parts into regexps,\n\n•   combining the regexps,\n\n•   and optimizing the final combined regexp.\n\nThese are also the typical steps involved in writing a computer program.  This makes perfect\nsense, because regular expressions are essentially programs written in a little computer\nlanguage that specifies patterns.\n"
                    },
                    {
                        "name": "Using regular expressions in Perl",
                        "content": "The last topic of Part 1 briefly covers how regexps are used in Perl programs.  Where do they\nfit into Perl syntax?\n\nWe have already introduced the matching operator in its default \"/regexp/\" and arbitrary\ndelimiter \"m!regexp!\" forms.  We have used the binding operator \"=~\" and its negation \"!~\" to\ntest for string matches.  Associated with the matching operator, we have discussed the single\nline \"/s\", multi-line \"/m\", case-insensitive \"/i\" and extended \"/x\" modifiers.  There are a\nfew more things you might want to know about matching operators.\n\nProhibiting substitution\n\nIf you change $pattern after the first substitution happens, Perl will ignore it.  If you\ndon't want any substitutions at all, use the special delimiter \"m''\":\n\n@pattern = ('Seuss');\nwhile (<>) {\nprint if m'@pattern';  # matches literal '@pattern', not 'Seuss'\n}\n\nSimilar to strings, \"m''\" acts like apostrophes on a regexp; all other 'm' delimiters act\nlike quotes.  If the regexp evaluates to the empty string, the regexp in the last successful\nmatch is used instead.  So we have\n\n\"dog\" =~ /d/;  # 'd' matches\n\"dogbert\" =~ //;  # this matches the 'd' regexp used before\n\nGlobal matching\n\nThe final two modifiers we will discuss here, \"/g\" and \"/c\", concern multiple matches.  The\nmodifier \"/g\" stands for global matching and allows the matching operator to match within a\nstring as many times as possible.  In scalar context, successive invocations against a string\nwill have \"/g\" jump from match to match, keeping track of position in the string as it goes\nalong.  You can get or set the position with the \"pos()\" function.\n\nThe use of \"/g\" is shown in the following example.  Suppose we have a string that consists of\nwords separated by spaces.  If we know how many words there are in advance, we could extract\nthe words using groupings:\n\n$x = \"cat dog house\"; # 3 words\n$x =~ /^\\s*(\\w+)\\s+(\\w+)\\s+(\\w+)\\s*$/; # matches,\n# $1 = 'cat'\n# $2 = 'dog'\n# $3 = 'house'\n\nBut what if we had an indeterminate number of words? This is the sort of task \"/g\" was made\nfor.  To extract all words, form the simple regexp \"(\\w+)\" and loop over all matches with\n\"/(\\w+)/g\":\n\nwhile ($x =~ /(\\w+)/g) {\nprint \"Word is $1, ends at position \", pos $x, \"\\n\";\n}\n\nprints\n\nWord is cat, ends at position 3\nWord is dog, ends at position 7\nWord is house, ends at position 13\n\nA failed match or changing the target string resets the position.  If you don't want the\nposition reset after failure to match, add the \"/c\", as in \"/regexp/gc\".  The current\nposition in the string is associated with the string, not the regexp.  This means that\ndifferent strings have different positions and their respective positions can be set or read\nindependently.\n\nIn list context, \"/g\" returns a list of matched groupings, or if there are no groupings, a\nlist of matches to the whole regexp.  So if we wanted just the words, we could use\n\n@words = ($x =~ /(\\w+)/g);  # matches,\n# $words[0] = 'cat'\n# $words[1] = 'dog'\n# $words[2] = 'house'\n\nClosely associated with the \"/g\" modifier is the \"\\G\" anchor.  The \"\\G\" anchor matches at the\npoint where the previous \"/g\" match left off.  \"\\G\" allows us to easily do context-sensitive\nmatching:\n\n$metric = 1;  # use metric units\n...\n$x = <FILE>;  # read in measurement\n$x =~ /^([+-]?\\d+)\\s*/g;  # get magnitude\n$weight = $1;\nif ($metric) { # error checking\nprint \"Units error!\" unless $x =~ /\\Gkg\\./g;\n}\nelse {\nprint \"Units error!\" unless $x =~ /\\Glbs\\./g;\n}\n$x =~ /\\G\\s+(widget|sprocket)/g;  # continue processing\n\nThe combination of \"/g\" and \"\\G\" allows us to process the string a bit at a time and use\narbitrary Perl logic to decide what to do next.  Currently, the \"\\G\" anchor is only fully\nsupported when used to anchor to the start of the pattern.\n\n\"\\G\" is also invaluable in processing fixed-length records with regexps.  Suppose we have a\nsnippet of coding region DNA, encoded as base pair letters \"ATCGTTGAAT...\" and we want to\nfind all the stop codons \"TGA\".  In a coding region, codons are 3-letter sequences, so we can\nthink of the DNA snippet as a sequence of 3-letter records.  The naive regexp\n\n# expanded, this is \"ATC GTT GAA TGC AAA TGA CAT GAC\"\n$dna = \"ATCGTTGAATGCAAATGACATGAC\";\n$dna =~ /TGA/;\n\ndoesn't work; it may match a \"TGA\", but there is no guarantee that the match is aligned with\ncodon boundaries, e.g., the substring \"GTT GAA\" gives a match.  A better solution is\n\nwhile ($dna =~ /(\\w\\w\\w)*?TGA/g) {  # note the minimal *?\nprint \"Got a TGA stop codon at position \", pos $dna, \"\\n\";\n}\n\nwhich prints\n\nGot a TGA stop codon at position 18\nGot a TGA stop codon at position 23\n\nPosition 18 is good, but position 23 is bogus.  What happened?\n\nThe answer is that our regexp works well until we get past the last real match.  Then the\nregexp will fail to match a synchronized \"TGA\" and start stepping ahead one character\nposition at a time, not what we want.  The solution is to use \"\\G\" to anchor the match to the\ncodon alignment:\n\nwhile ($dna =~ /\\G(\\w\\w\\w)*?TGA/g) {\nprint \"Got a TGA stop codon at position \", pos $dna, \"\\n\";\n}\n\nThis prints\n\nGot a TGA stop codon at position 18\n\nwhich is the correct answer.  This example illustrates that it is important not only to match\nwhat is desired, but to reject what is not desired.\n\n(There are other regexp modifiers that are available, such as \"/o\", but their specialized\nuses are beyond the scope of this introduction.  )\n\nSearch and replace\n\nRegular expressions also play a big role in search and replace operations in Perl.  Search\nand replace is accomplished with the \"s///\" operator.  The general form is\n\"s/regexp/replacement/modifiers\", with everything we know about regexps and modifiers\napplying in this case as well.  The replacement is a Perl double-quoted string that replaces\nin the string whatever is matched with the \"regexp\".  The operator \"=~\" is also used here to\nassociate a string with \"s///\".  If matching against $, the \"$ =~\" can be dropped.  If\nthere is a match, \"s///\" returns the number of substitutions made; otherwise it returns\nfalse.  Here are a few examples:\n\n$x = \"Time to feed the cat!\";\n$x =~ s/cat/hacker/;   # $x contains \"Time to feed the hacker!\"\nif ($x =~ s/^(Time.*hacker)!$/$1 now!/) {\n$moreinsistent = 1;\n}\n$y = \"'quoted words'\";\n$y =~ s/^'(.*)'$/$1/;  # strip single quotes,\n# $y contains \"quoted words\"\n\nIn the last example, the whole string was matched, but only the part inside the single quotes\nwas grouped.  With the \"s///\" operator, the matched variables $1, $2, etc. are immediately\navailable for use in the replacement expression, so we use $1 to replace the quoted string\nwith just what was quoted.  With the global modifier, \"s///g\" will search and replace all\noccurrences of the regexp in the string:\n\n$x = \"I batted 4 for 4\";\n$x =~ s/4/four/;   # doesn't do it all:\n# $x contains \"I batted four for 4\"\n$x = \"I batted 4 for 4\";\n$x =~ s/4/four/g;  # does it all:\n# $x contains \"I batted four for four\"\n\nIf you prefer \"regex\" over \"regexp\" in this tutorial, you could use the following program to\nreplace it:\n\n% cat > simplereplace\n#!/usr/bin/perl\n$regexp = shift;\n$replacement = shift;\nwhile (<>) {\ns/$regexp/$replacement/g;\nprint;\n}\n^D\n\n% simplereplace regexp regex perlretut.pod\n\nIn \"simplereplace\" we used the \"s///g\" modifier to replace all occurrences of the regexp on\neach line.  (Even though the regular expression appears in a loop, Perl is smart enough to\ncompile it only once.)  As with \"simplegrep\", both the \"print\" and the\n\"s/$regexp/$replacement/g\" use $ implicitly.\n\nIf you don't want \"s///\" to change your original variable you can use the non-destructive\nsubstitute modifier, \"s///r\".  This changes the behavior so that \"s///r\" returns the final\nsubstituted string (instead of the number of substitutions):\n\n$x = \"I like dogs.\";\n$y = $x =~ s/dogs/cats/r;\nprint \"$x $y\\n\";\n\nThat example will print \"I like dogs. I like cats\". Notice the original $x variable has not\nbeen affected. The overall result of the substitution is instead stored in $y. If the\nsubstitution doesn't affect anything then the original string is returned:\n\n$x = \"I like dogs.\";\n$y = $x =~ s/elephants/cougars/r;\nprint \"$x $y\\n\"; # prints \"I like dogs. I like dogs.\"\n\nOne other interesting thing that the \"s///r\" flag allows is chaining substitutions:\n\n$x = \"Cats are great.\";\nprint $x =~ s/Cats/Dogs/r =~ s/Dogs/Frogs/r =~\ns/Frogs/Hedgehogs/r, \"\\n\";\n# prints \"Hedgehogs are great.\"\n\nA modifier available specifically to search and replace is the \"s///e\" evaluation modifier.\n\"s///e\" treats the replacement text as Perl code, rather than a double-quoted string.  The\nvalue that the code returns is substituted for the matched substring.  \"s///e\" is useful if\nyou need to do a bit of computation in the process of replacing text.  This example counts\ncharacter frequencies in a line:\n\n$x = \"Bill the cat\";\n$x =~ s/(.)/$chars{$1}++;$1/eg; # final $1 replaces char with itself\nprint \"frequency of '$' is $chars{$}\\n\"\nforeach (sort {$chars{$b} <=> $chars{$a}} keys %chars);\n\nThis prints\n\nfrequency of ' ' is 2\nfrequency of 't' is 2\nfrequency of 'l' is 2\nfrequency of 'B' is 1\nfrequency of 'c' is 1\nfrequency of 'e' is 1\nfrequency of 'h' is 1\nfrequency of 'i' is 1\nfrequency of 'a' is 1\n\nAs with the match \"m//\" operator, \"s///\" can use other delimiters, such as \"s!!!\" and\n\"s{}{}\", and even \"s{}//\".  If single quotes are used \"s'''\", then the regexp and replacement\nare treated as single-quoted strings and there are no variable substitutions.  \"s///\" in list\ncontext returns the same thing as in scalar context, i.e., the number of matches.\n\nThe split function\n\nThe \"split()\" function is another place where a regexp is used.  \"split /regexp/, string,\nlimit\" separates the \"string\" operand into a list of substrings and returns that list.  The\nregexp must be designed to match whatever constitutes the separators for the desired\nsubstrings.  The \"limit\", if present, constrains splitting into no more than \"limit\" number\nof strings.  For example, to split a string into words, use\n\n$x = \"Calvin and Hobbes\";\n@words = split /\\s+/, $x;  # $word[0] = 'Calvin'\n# $word[1] = 'and'\n# $word[2] = 'Hobbes'\n\nIf the empty regexp \"//\" is used, the regexp always matches and the string is split into\nindividual characters.  If the regexp has groupings, then the resulting list contains the\nmatched substrings from the groupings as well.  For instance,\n\n$x = \"/usr/bin/perl\";\n@dirs = split m!/!, $x;  # $dirs[0] = ''\n# $dirs[1] = 'usr'\n# $dirs[2] = 'bin'\n# $dirs[3] = 'perl'\n@parts = split m!(/)!, $x;  # $parts[0] = ''\n# $parts[1] = '/'\n# $parts[2] = 'usr'\n# $parts[3] = '/'\n# $parts[4] = 'bin'\n# $parts[5] = '/'\n# $parts[6] = 'perl'\n\nSince the first character of $x matched the regexp, \"split\" prepended an empty initial\nelement to the list.\n\nIf you have read this far, congratulations! You now have all the basic tools needed to use\nregular expressions to solve a wide range of text processing problems.  If this is your first\ntime through the tutorial, why not stop here and play around with regexps a while....  Part 2\nconcerns the more esoteric aspects of regular expressions and those concepts certainly aren't\nneeded right at the start.\n"
                    },
                    {
                        "name": "Part 2: Power tools",
                        "content": "OK, you know the basics of regexps and you want to know more.  If matching regular\nexpressions is analogous to a walk in the woods, then the tools discussed in Part 1 are\nanalogous to topo maps and a compass, basic tools we use all the time.  Most of the tools in\npart 2 are analogous to flare guns and satellite phones.  They aren't used too often on a\nhike, but when we are stuck, they can be invaluable.\n\nWhat follows are the more advanced, less used, or sometimes esoteric capabilities of Perl\nregexps.  In Part 2, we will assume you are comfortable with the basics and concentrate on\nthe advanced features.\n"
                    },
                    {
                        "name": "More on characters, strings, and character classes",
                        "content": "There are a number of escape sequences and character classes that we haven't covered yet.\n\nThere are several escape sequences that convert characters or strings between upper and lower\ncase, and they are also available within patterns.  \"\\l\" and \"\\u\" convert the next character\nto lower or upper case, respectively:\n\n$x = \"perl\";\n$string =~ /\\u$x/;  # matches 'Perl' in $string\n$x = \"M(rs?|s)\\\\.\"; # note the double backslash\n$string =~ /\\l$x/;  # matches 'mr.', 'mrs.', and 'ms.',\n\nA \"\\L\" or \"\\U\" indicates a lasting conversion of case, until terminated by \"\\E\" or thrown\nover by another \"\\U\" or \"\\L\":\n\n$x = \"This word is in lower case:\\L SHOUT\\E\";\n$x =~ /shout/;       # matches\n$x = \"I STILL KEYPUNCH CARDS FOR MY 360\";\n$x =~ /\\Ukeypunch/;  # matches punch card string\n\nIf there is no \"\\E\", case is converted until the end of the string. The regexps \"\\L\\u$word\"\nor \"\\u\\L$word\" convert the first character of $word to uppercase and the rest of the\ncharacters to lowercase.\n\nControl characters can be escaped with \"\\c\", so that a control-Z character would be matched\nwith \"\\cZ\".  The escape sequence \"\\Q\"...\"\\E\" quotes, or protects most non-alphabetic\ncharacters.   For instance,\n\n$x = \"\\QThat !^*&%~& cat!\";\n$x =~ /\\Q!^*&%~&\\E/;  # check for rough language\n\nIt does not protect '$' or '@', so that variables can still be substituted.\n\n\"\\Q\", \"\\L\", \"\\l\", \"\\U\", \"\\u\" and \"\\E\" are actually part of double-quotish syntax, and not\npart of regexp syntax proper.  They will work if they appear in a regular expression embedded\ndirectly in a program, but not when contained in a string that is interpolated in a pattern.\n\nPerl regexps can handle more than just the standard ASCII character set.  Perl supports\nUnicode, a standard for representing the alphabets from virtually all of the world's written\nlanguages, and a host of symbols.  Perl's text strings are Unicode strings, so they can\ncontain characters with a value (codepoint or character number) higher than 255.\n\nWhat does this mean for regexps? Well, regexp users don't need to know much about Perl's\ninternal representation of strings.  But they do need to know 1) how to represent Unicode\ncharacters in a regexp and 2) that a matching operation will treat the string to be searched\nas a sequence of characters, not bytes.  The answer to 1) is that Unicode characters greater\nthan \"chr(255)\" are represented using the \"\\x{hex}\" notation, because \"\\x\"XY (without curly\nbraces and XY are two hex digits) doesn't go further than 255.  (Starting in Perl 5.14, if\nyou're an octal fan, you can also use \"\\o{oct}\".)\n\n/\\x{263a}/;   # match a Unicode smiley face :)\n/\\x{ 263a }/; # Same\n\nNOTE: In Perl 5.6.0 it used to be that one needed to say \"use utf8\" to use any Unicode\nfeatures.  This is no longer the case: for almost all Unicode processing, the explicit \"utf8\"\npragma is not needed.  (The only case where it matters is if your Perl script is in Unicode\nand encoded in UTF-8, then an explicit \"use utf8\" is needed.)\n\nFiguring out the hexadecimal sequence of a Unicode character you want or deciphering someone\nelse's hexadecimal Unicode regexp is about as much fun as programming in machine code.  So\nanother way to specify Unicode characters is to use the named character escape sequence\n\"\\N{name}\".  name is a name for the Unicode character, as specified in the Unicode standard.\nFor instance, if we wanted to represent or match the astrological sign for the planet\nMercury, we could use\n\n$x = \"abc\\N{MERCURY}def\";\n$x =~ /\\N{MERCURY}/;   # matches\n$x =~ /\\N{ MERCURY }/; # Also matches\n\nOne can also use \"short\" names:\n\nprint \"\\N{GREEK SMALL LETTER SIGMA} is called sigma.\\n\";\nprint \"\\N{greek:Sigma} is an upper-case sigma.\\n\";\n\nYou can also restrict names to a certain alphabet by specifying the charnames pragma:\n\nuse charnames qw(greek);\nprint \"\\N{sigma} is Greek sigma\\n\";\n\nAn index of character names is available on-line from the Unicode Consortium,\n<https://www.unicode.org/charts/charindex.html>; explanatory material with links to other\nresources at <https://www.unicode.org/standard/where>.\n\nStarting in Perl v5.32, an alternative to \"\\N{...}\" for full names is available, and that is\nto say\n\n/\\p{Name=greek small letter sigma}/\n\nThe casing of the character name is irrelevant when used in \"\\p{}\", as are most spaces,\nunderscores and hyphens.  (A few outlier characters cause problems with ignoring all of them\nalways.  The details (which you can look up when you get more proficient, and if ever needed)\nare in <https://www.unicode.org/reports/tr44/tr44-24.html#UAX44-LM2>).\n\nThe answer to requirement 2) is that a regexp (mostly) uses Unicode characters.  The \"mostly\"\nis for messy backward compatibility reasons, but starting in Perl 5.14, any regexp compiled\nin the scope of a \"use feature 'unicodestrings'\" (which is automatically turned on within\nthe scope of a \"use 5.012\" or higher) will turn that \"mostly\" into \"always\".  If you want to\nhandle Unicode properly, you should ensure that 'unicodestrings' is turned on.  Internally,\nthis is encoded to bytes using either UTF-8 or a native 8 bit encoding, depending on the\nhistory of the string, but conceptually it is a sequence of characters, not bytes. See\nperlunitut for a tutorial about that.\n\nLet us now discuss Unicode character classes, most usually called \"character properties\".\nThese are represented by the \"\\p{name}\" escape sequence.  The negation of this is \"\\P{name}\".\nFor example, to match lower and uppercase characters,\n\n$x = \"BOB\";\n$x =~ /^\\p{IsUpper}/;   # matches, uppercase char class\n$x =~ /^\\P{IsUpper}/;   # doesn't match, char class sans uppercase\n$x =~ /^\\p{IsLower}/;   # doesn't match, lowercase char class\n$x =~ /^\\P{IsLower}/;   # matches, char class sans lowercase\n\n(The \"\"Is\"\" is optional.)\n\nThere are many, many Unicode character properties.  For the full list see perluniprops.  Most\nof them have synonyms with shorter names, also listed there.  Some synonyms are a single\ncharacter.  For these, you can drop the braces.  For instance, \"\\pM\" is the same thing as\n\"\\p{Mark}\", meaning things like accent marks.\n\nThe Unicode \"\\p{Script}\" and \"\\p{ScriptExtensions}\" properties are used to categorize every\nUnicode character into the language script it is written in.  For example, English, French,\nand a bunch of other European languages are written in the Latin script.  But there is also\nthe Greek script, the Thai script, the Katakana script, etc.  (\"Script\" is an older, less\nadvanced, form of \"ScriptExtensions\", retained only for backwards compatibility.)  You can\ntest whether a character is in a particular script  with, for example \"\\p{Latin}\",\n\"\\p{Greek}\", or \"\\p{Katakana}\".  To test if it isn't in the Balinese script, you would use\n\"\\P{Balinese}\".  (These all use \"ScriptExtensions\" under the hood, as that gives better\nresults.)\n\nWhat we have described so far is the single form of the \"\\p{...}\" character classes.  There\nis also a compound form which you may run into.  These look like \"\\p{name=value}\" or\n\"\\p{name:value}\" (the equals sign and colon can be used interchangeably).  These are more\ngeneral than the single form, and in fact most of the single forms are just Perl-defined\nshortcuts for common compound forms.  For example, the script examples in the previous\nparagraph could be written equivalently as \"\\p{ScriptExtensions=Latin}\",\n\"\\p{ScriptExtensions:Greek}\", \"\\p{scriptextensions=katakana}\", and\n\"\\P{scriptextensions=balinese}\" (case is irrelevant between the \"{}\" braces).  You may never\nhave to use the compound forms, but sometimes it is necessary, and their use can make your\ncode easier to understand.\n\n\"\\X\" is an abbreviation for a character class that comprises a Unicode extended grapheme\ncluster.  This represents a \"logical character\": what appears to be a single character, but\nmay be represented internally by more than one.  As an example, using the Unicode full names,\ne.g., \"A + COMBINING RING\" is a grapheme cluster with base character \"A\" and combining\ncharacter \"COMBINING RING, which translates in Danish to \"A\" with the circle atop it, as in\nthe word Ångstrom.\n\nFor the full and latest information about Unicode see the latest Unicode standard, or the\nUnicode Consortium's website <https://www.unicode.org>\n\nAs if all those classes weren't enough, Perl also defines POSIX-style character classes.\nThese have the form \"[:name:]\", with name the name of the POSIX class.  The POSIX classes are\n\"alpha\", \"alnum\", \"ascii\", \"cntrl\", \"digit\", \"graph\", \"lower\", \"print\", \"punct\", \"space\",\n\"upper\", and \"xdigit\", and two extensions, \"word\" (a Perl extension to match \"\\w\"), and\n\"blank\" (a GNU extension).  The \"/a\" modifier restricts these to matching just in the ASCII\nrange; otherwise they can match the same as their corresponding Perl Unicode classes:\n\"[:upper:]\" is the same as \"\\p{IsUpper}\", etc.  (There are some exceptions and gotchas with\nthis; see perlrecharclass for a full discussion.) The \"[:digit:]\", \"[:word:]\", and\n\"[:space:]\" correspond to the familiar \"\\d\", \"\\w\", and \"\\s\" character classes.  To negate a\nPOSIX class, put a '^' in front of the name, so that, e.g., \"[:^digit:]\" corresponds to \"\\D\"\nand, under Unicode, \"\\P{IsDigit}\".  The Unicode and POSIX character classes can be used just\nlike \"\\d\", with the exception that POSIX character classes can only be used inside of a\ncharacter class:\n\n/\\s+[abc[:digit:]xyz]\\s*/;  # match a,b,c,x,y,z, or a digit\n/^=item\\s[[:digit:]]/;      # match '=item',\n# followed by a space and a digit\n/\\s+[abc\\p{IsDigit}xyz]\\s+/;  # match a,b,c,x,y,z, or a digit\n/^=item\\s\\p{IsDigit}/;        # match '=item',\n# followed by a space and a digit\n\nWhew! That is all the rest of the characters and character classes.\n"
                    },
                    {
                        "name": "Compiling and saving regular expressions",
                        "content": "In Part 1 we mentioned that Perl compiles a regexp into a compact sequence of opcodes.  Thus,\na compiled regexp is a data structure that can be stored once and used again and again.  The\nregexp quote \"qr//\" does exactly that: \"qr/string/\" compiles the \"string\" as a regexp and\ntransforms the result into a form that can be assigned to a variable:\n\n$reg = qr/foo+bar?/;  # reg contains a compiled regexp\n\nThen $reg can be used as a regexp:\n\n$x = \"fooooba\";\n$x =~ $reg;     # matches, just like /foo+bar?/\n$x =~ /$reg/;   # same thing, alternate form\n\n$reg can also be interpolated into a larger regexp:\n\n$x =~ /(abc)?$reg/;  # still matches\n\nAs with the matching operator, the regexp quote can use different delimiters, e.g., \"qr!!\",\n\"qr{}\" or \"qr~~\".  Apostrophes as delimiters (\"qr''\") inhibit any interpolation.\n\nPre-compiled regexps are useful for creating dynamic matches that don't need to be recompiled\neach time they are encountered.  Using pre-compiled regexps, we write a \"grepstep\" program\nwhich greps for a sequence of patterns, advancing to the next pattern as soon as one has been\nsatisfied.\n\n% cat > grepstep\n#!/usr/bin/perl\n# grepstep - match <number> regexps, one after the other\n# usage: multigrep <number> regexp1 regexp2 ... file1 file2 ...\n\n$number = shift;\n$regexp[$] = shift foreach (0..$number-1);\n@compiled = map qr/$/, @regexp;\nwhile ($line = <>) {\nif ($line =~ /$compiled[0]/) {\nprint $line;\nshift @compiled;\nlast unless @compiled;\n}\n}\n^D\n\n% grepstep 3 shift print last grepstep\n$number = shift;\nprint $line;\nlast unless @compiled;\n\nStoring pre-compiled regexps in an array @compiled allows us to simply loop through the\nregexps without any recompilation, thus gaining flexibility without sacrificing speed.\n"
                    },
                    {
                        "name": "Composing regular expressions at runtime",
                        "content": "Backtracking is more efficient than repeated tries with different regular expressions.  If\nthere are several regular expressions and a match with any of them is acceptable, then it is\npossible to combine them into a set of alternatives.  If the individual expressions are input\ndata, this can be done by programming a join operation.  We'll exploit this idea in an\nimproved version of the \"simplegrep\" program: a program that matches multiple patterns:\n\n% cat > multigrep\n#!/usr/bin/perl\n# multigrep - match any of <number> regexps\n# usage: multigrep <number> regexp1 regexp2 ... file1 file2 ...\n\n$number = shift;\n$regexp[$] = shift foreach (0..$number-1);\n$pattern = join '|', @regexp;\n\nwhile ($line = <>) {\nprint $line if $line =~ /$pattern/;\n}\n^D\n\n% multigrep 2 shift for multigrep\n$number = shift;\n$regexp[$] = shift foreach (0..$number-1);\n\nSometimes it is advantageous to construct a pattern from the input that is to be analyzed and\nuse the permissible values on the left hand side of the matching operations.  As an example\nfor this somewhat paradoxical situation, let's assume that our input contains a command verb\nwhich should match one out of a set of available command verbs, with the additional twist\nthat commands may be abbreviated as long as the given string is unique. The program below\ndemonstrates the basic algorithm.\n\n% cat > keymatch\n#!/usr/bin/perl\n$kwds = 'copy compare list print';\nwhile( $cmd = <> ){\n$cmd =~ s/^\\s+|\\s+$//g;  # trim leading and trailing spaces\nif( ( @matches = $kwds =~ /\\b$cmd\\w*/g ) == 1 ){\nprint \"command: '@matches'\\n\";\n} elsif( @matches == 0 ){\nprint \"no such command: '$cmd'\\n\";\n} else {\nprint \"not unique: '$cmd' (could be one of: @matches)\\n\";\n}\n}\n^D\n\n% keymatch\nli\ncommand: 'list'\nco\nnot unique: 'co' (could be one of: copy compare)\nprinter\nno such command: 'printer'\n\nRather than trying to match the input against the keywords, we match the combined set of\nkeywords against the input.  The pattern matching operation \"$kwds =~ /\\b($cmd\\w*)/g\" does\nseveral things at the same time. It makes sure that the given command begins where a keyword\nbegins (\"\\b\"). It tolerates abbreviations due to the added \"\\w*\". It tells us the number of\nmatches (\"scalar @matches\") and all the keywords that were actually matched.  You could\nhardly ask for more.\n"
                    },
                    {
                        "name": "Embedding comments and modifiers in a regular expression",
                        "content": "Starting with this section, we will be discussing Perl's set of extended patterns.  These are\nextensions to the traditional regular expression syntax that provide powerful new tools for\npattern matching.  We have already seen extensions in the form of the minimal matching\nconstructs \"??\", \"*?\", \"+?\", \"{n,m}?\", \"{n,}?\", and \"{,n}?\".  Most of the extensions below\nhave the form \"(?char...)\", where the \"char\" is a character that determines the type of\nextension.\n\nThe first extension is an embedded comment \"(?#text)\".  This embeds a comment into the\nregular expression without affecting its meaning.  The comment should not have any closing\nparentheses in the text.  An example is\n\n/(?# Match an integer:)[+-]?\\d+/;\n\nThis style of commenting has been largely superseded by the raw, freeform commenting that is\nallowed with the \"/x\" modifier.\n\nMost modifiers, such as \"/i\", \"/m\", \"/s\" and \"/x\" (or any combination thereof) can also be\nembedded in a regexp using \"(?i)\", \"(?m)\", \"(?s)\", and \"(?x)\".  For instance,\n\n/(?i)yes/;  # match 'yes' case insensitively\n/yes/i;     # same thing\n/(?x)(          # freeform version of an integer regexp\n[+-]?  # match an optional sign\n\\d+    # match a sequence of digits\n)\n/x;\n\nEmbedded modifiers can have two important advantages over the usual modifiers.  Embedded\nmodifiers allow a custom set of modifiers for each regexp pattern.  This is great for\nmatching an array of regexps that must have different modifiers:\n\n$pattern[0] = '(?i)doctor';\n$pattern[1] = 'Johnson';\n...\nwhile (<>) {\nforeach $patt (@pattern) {\nprint if /$patt/;\n}\n}\n\nThe second advantage is that embedded modifiers (except \"/p\", which modifies the entire\nregexp) only affect the regexp inside the group the embedded modifier is contained in.  So\ngrouping can be used to localize the modifier's effects:\n\n/Answer: ((?i)yes)/;  # matches 'Answer: yes', 'Answer: YES', etc.\n\nEmbedded modifiers can also turn off any modifiers already present by using, e.g., \"(?-i)\".\nModifiers can also be combined into a single expression, e.g., \"(?s-i)\" turns on single line\nmode and turns off case insensitivity.\n\nEmbedded modifiers may also be added to a non-capturing grouping.  \"(?i-m:regexp)\" is a non-\ncapturing grouping that matches \"regexp\" case insensitively and turns off multi-line mode.\n"
                    },
                    {
                        "name": "Looking ahead and looking behind",
                        "content": "This section concerns the lookahead and lookbehind assertions.  First, a little background.\n\nIn Perl regular expressions, most regexp elements \"eat up\" a certain amount of string when\nthey match.  For instance, the regexp element \"[abc]\" eats up one character of the string\nwhen it matches, in the sense that Perl moves to the next character position in the string\nafter the match.  There are some elements, however, that don't eat up characters (advance the\ncharacter position) if they match.  The examples we have seen so far are the anchors.  The\nanchor '^' matches the beginning of the line, but doesn't eat any characters.  Similarly, the\nword boundary anchor \"\\b\" matches wherever a character matching \"\\w\" is next to a character\nthat doesn't, but it doesn't eat up any characters itself.  Anchors are examples of zero-\nwidth assertions: zero-width, because they consume no characters, and assertions, because\nthey test some property of the string.  In the context of our walk in the woods analogy to\nregexp matching, most regexp elements move us along a trail, but anchors have us stop a\nmoment and check our surroundings.  If the local environment checks out, we can proceed\nforward.  But if the local environment doesn't satisfy us, we must backtrack.\n\nChecking the environment entails either looking ahead on the trail, looking behind, or both.\n'^' looks behind, to see that there are no characters before.  '$' looks ahead, to see that\nthere are no characters after.  \"\\b\" looks both ahead and behind, to see if the characters on\neither side differ in their \"word-ness\".\n\nThe lookahead and lookbehind assertions are generalizations of the anchor concept.  Lookahead\nand lookbehind are zero-width assertions that let us specify which characters we want to test\nfor.  The lookahead assertion is denoted by \"(?=regexp)\" or (starting in 5.32, experimentally\nin 5.28) \"(*pla:regexp)\" or \"(*positivelookahead:regexp)\"; and the lookbehind assertion is\ndenoted by \"(?<=fixed-regexp)\" or (starting in 5.32, experimentally in 5.28)\n\"(*plb:fixed-regexp)\" or \"(*positivelookbehind:fixed-regexp)\".  Some examples are\n\n$x = \"I catch the housecat 'Tom-cat' with catnip\";\n$x =~ /cat(*pla:\\s)/;   # matches 'cat' in 'housecat'\n@catwords = ($x =~ /(?<=\\s)cat\\w+/g);  # matches,\n# $catwords[0] = 'catch'\n# $catwords[1] = 'catnip'\n$x =~ /\\bcat\\b/;  # matches 'cat' in 'Tom-cat'\n$x =~ /(?<=\\s)cat(?=\\s)/; # doesn't match; no isolated 'cat' in\n# middle of $x\n\nNote that the parentheses in these are non-capturing, since these are zero-width assertions.\nThus in the second regexp, the substrings captured are those of the whole regexp itself.\nLookahead can match arbitrary regexps, but lookbehind prior to 5.30 \"(?<=fixed-regexp)\" only\nworks for regexps of fixed width, i.e., a fixed number of characters long.  Thus\n\"(?<=(ab|bc))\" is fine, but \"(?<=(ab)*)\" prior to 5.30 is not.\n\nThe negated versions of the lookahead and lookbehind assertions are denoted by \"(?!regexp)\"\nand \"(?<!fixed-regexp)\" respectively.  Or, starting in 5.32 (experimentally in 5.28),\n\"(*nla:regexp)\", \"(*negativelookahead:regexp)\", \"(*nlb:regexp)\", or\n\"(*negativelookbehind:regexp)\".  They evaluate true if the regexps do not match:\n\n$x = \"foobar\";\n$x =~ /foo(?!bar)/;  # doesn't match, 'bar' follows 'foo'\n$x =~ /foo(?!baz)/;  # matches, 'baz' doesn't follow 'foo'\n$x =~ /(?<!\\s)foo/;  # matches, there is no \\s before 'foo'\n\nHere is an example where a string containing blank-separated words, numbers and single dashes\nis to be split into its components.  Using \"/\\s+/\" alone won't work, because spaces are not\nrequired between dashes, or a word or a dash. Additional places for a split are established\nby looking ahead and behind:\n\n$str = \"one two - --6-8\";\n@toks = split / \\s+              # a run of spaces\n| (?<=\\S) (?=-)    # any non-space followed by '-'\n| (?<=-)  (?=\\S)   # a '-' followed by any non-space\n/x, $str;          # @toks = qw(one two - - - 6 - 8)\n"
                    },
                    {
                        "name": "Using independent subexpressions to prevent backtracking",
                        "content": "Independent subexpressions (or atomic subexpressions) are regular expressions, in the context\nof a larger regular expression, that function independently of the larger regular expression.\nThat is, they consume as much or as little of the string as they wish without regard for the\nability of the larger regexp to match.  Independent subexpressions are represented by\n\"(?>regexp)\" or (starting in 5.32, experimentally in 5.28) \"(*atomic:regexp)\".  We can\nillustrate their behavior by first considering an ordinary regexp:\n\n$x = \"ab\";\n$x =~ /a*ab/;  # matches\n\nThis obviously matches, but in the process of matching, the subexpression \"a*\" first grabbed\nthe 'a'.  Doing so, however, wouldn't allow the whole regexp to match, so after backtracking,\n\"a*\" eventually gave back the 'a' and matched the empty string.  Here, what \"a*\" matched was\ndependent on what the rest of the regexp matched.\n\nContrast that with an independent subexpression:\n\n$x =~ /(?>a*)ab/;  # doesn't match!\n\nThe independent subexpression \"(?>a*)\" doesn't care about the rest of the regexp, so it sees\nan 'a' and grabs it.  Then the rest of the regexp \"ab\" cannot match.  Because \"(?>a*)\" is\nindependent, there is no backtracking and the independent subexpression does not give up its\n'a'.  Thus the match of the regexp as a whole fails.  A similar behavior occurs with\ncompletely independent regexps:\n\n$x = \"ab\";\n$x =~ /a*/g;   # matches, eats an 'a'\n$x =~ /\\Gab/g; # doesn't match, no 'a' available\n\nHere \"/g\" and \"\\G\" create a \"tag team\" handoff of the string from one regexp to the other.\nRegexps with an independent subexpression are much like this, with a handoff of the string to\nthe independent subexpression, and a handoff of the string back to the enclosing regexp.\n\nThe ability of an independent subexpression to prevent backtracking can be quite useful.\nSuppose we want to match a non-empty string enclosed in parentheses up to two levels deep.\nThen the following regexp matches:\n\n$x = \"abc(de(fg)h\";  # unbalanced parentheses\n$x =~ /\\( ( [ ^ () ]+ | \\( [ ^ () ]* \\) )+ \\)/xx;\n\nThe regexp matches an open parenthesis, one or more copies of an alternation, and a close\nparenthesis.  The alternation is two-way, with the first alternative \"[^()]+\" matching a\nsubstring with no parentheses and the second alternative \"\\([^()]*\\)\"  matching a substring\ndelimited by parentheses.  The problem with this regexp is that it is pathological: it has\nnested indeterminate quantifiers of the form \"(a+|b)+\".  We discussed in Part 1 how nested\nquantifiers like this could take an exponentially long time to execute if no match were\npossible.  To prevent the exponential blowup, we need to prevent useless backtracking at some\npoint.  This can be done by enclosing the inner quantifier as an independent subexpression:\n\n$x =~ /\\( ( (?> [ ^ () ]+ ) | \\([ ^ () ]* \\) )+ \\)/xx;\n\nHere, \"(?>[^()]+)\" breaks the degeneracy of string partitioning by gobbling up as much of the\nstring as possible and keeping it.   Then match failures fail much more quickly.\n"
                    },
                    {
                        "name": "Conditional expressions",
                        "content": "A conditional expression is a form of if-then-else statement that allows one to choose which\npatterns are to be matched, based on some condition.  There are two types of conditional\nexpression: \"(?(condition)yes-regexp)\" and \"(?(condition)yes-regexp|no-regexp)\".\n\"(?(condition)yes-regexp)\" is like an 'if () {}' statement in Perl.  If the condition is\ntrue, the yes-regexp will be matched.  If the condition is false, the yes-regexp will be\nskipped and Perl will move onto the next regexp element.  The second form is like an\n'if () {} else {}' statement in Perl.  If the condition is true, the yes-regexp will be\nmatched, otherwise the no-regexp will be matched.\n\nThe condition can have several forms.  The first form is simply an integer in parentheses\n\"(integer)\".  It is true if the corresponding backreference \"\\integer\" matched earlier in the\nregexp.  The same thing can be done with a name associated with a capture group, written as\n\"(<name>)\" or \"('name')\".  The second form is a bare zero-width assertion \"(?...)\", either a\nlookahead, a lookbehind, or a code assertion (discussed in the next section).  The third set\nof forms provides tests that return true if the expression is executed within a recursion\n(\"(R)\") or is being called from some capturing group, referenced either by number (\"(R1)\",\n\"(R2)\",...) or by name (\"(R&name)\").\n\nThe integer or name form of the \"condition\" allows us to choose, with more flexibility, what\nto match based on what matched earlier in the regexp. This searches for words of the form\n\"$x$x\" or \"$x$y$y$x\":\n\n% simplegrep '^(\\w+)(\\w+)?(?(2)\\g2\\g1|\\g1)$' /usr/dict/words\nberiberi\ncoco\ncouscous\ndeed\n...\ntoot\ntoto\ntutu\n\nThe lookbehind \"condition\" allows, along with backreferences, an earlier part of the match to\ninfluence a later part of the match.  For instance,\n\n/[ATGC]+(?(?<=AA)G|C)$/;\n\nmatches a DNA sequence such that it either ends in \"AAG\", or some other base pair combination\nand 'C'.  Note that the form is \"(?(?<=AA)G|C)\" and not \"(?((?<=AA))G|C)\"; for the lookahead,\nlookbehind or code assertions, the parentheses around the conditional are not needed.\n"
                    },
                    {
                        "name": "Defining named patterns",
                        "content": "Some regular expressions use identical subpatterns in several places.  Starting with Perl\n5.10, it is possible to define named subpatterns in a section of the pattern so that they can\nbe called up by name anywhere in the pattern.  This syntactic pattern for this definition\ngroup is \"(?(DEFINE)(?<name>pattern)...)\".  An insertion of a named pattern is written as\n\"(?&name)\".\n\nThe example below illustrates this feature using the pattern for floating point numbers that\nwas presented earlier on.  The three subpatterns that are used more than once are the\noptional sign, the digit sequence for an integer and the decimal fraction.  The \"DEFINE\"\ngroup at the end of the pattern contains their definition.  Notice that the decimal fraction\npattern is the first place where we can reuse the integer pattern.\n\n/^ (?&osg)\\ * ( (?&int)(?&dec)? | (?&dec) )\n(?: [eE](?&osg)(?&int) )?\n$\n(?(DEFINE)\n(?<osg>[-+]?)         # optional sign\n(?<int>\\d++)          # integer\n(?<dec>\\.(?&int))     # decimal fraction\n)/x\n"
                    },
                    {
                        "name": "Recursive patterns",
                        "content": "This feature (introduced in Perl 5.10) significantly extends the power of Perl's pattern\nmatching.  By referring to some other capture group anywhere in the pattern with the\nconstruct \"(?group-ref)\", the pattern within the referenced group is used as an independent\nsubpattern in place of the group reference itself.  Because the group reference may be\ncontained within the group it refers to, it is now possible to apply pattern matching to\ntasks that hitherto required a recursive parser.\n\nTo illustrate this feature, we'll design a pattern that matches if a string contains a\npalindrome. (This is a word or a sentence that, while ignoring spaces, interpunctuation and\ncase, reads the same backwards as forwards. We begin by observing that the empty string or a\nstring containing just one word character is a palindrome. Otherwise it must have a word\ncharacter up front and the same at its end, with another palindrome in between.\n\n/(?: (\\w) (?...Here be a palindrome...) \\g{ -1 } | \\w? )/x\n\nAdding \"\\W*\" at either end to eliminate what is to be ignored, we already have the full\npattern:\n\nmy $pp = qr/^(\\W* (?: (\\w) (?1) \\g{-1} | \\w? ) \\W*)$/ix;\nfor $s ( \"saippuakauppias\", \"A man, a plan, a canal: Panama!\" ){\nprint \"'$s' is a palindrome\\n\" if $s =~ /$pp/;\n}\n\nIn \"(?...)\" both absolute and relative backreferences may be used.  The entire pattern can be\nreinserted with \"(?R)\" or \"(?0)\".  If you prefer to name your groups, you can use \"(?&name)\"\nto recurse into that group.\n"
                    },
                    {
                        "name": "A bit of magic: executing Perl code in a regular expression",
                        "content": "Normally, regexps are a part of Perl expressions.  Code evaluation expressions turn that\naround by allowing arbitrary Perl code to be a part of a regexp.  A code evaluation\nexpression is denoted \"(?{code})\", with code a string of Perl statements.\n\nCode expressions are zero-width assertions, and the value they return depends on their\nenvironment.  There are two possibilities: either the code expression is used as a\nconditional in a conditional expression \"(?(condition)...)\", or it is not.  If the code\nexpression is a conditional, the code is evaluated and the result (i.e., the result of the\nlast statement) is used to determine truth or falsehood.  If the code expression is not used\nas a conditional, the assertion always evaluates true and the result is put into the special\nvariable $^R.  The variable $^R can then be used in code expressions later in the regexp.\nHere are some silly examples:\n\n$x = \"abcdef\";\n$x =~ /abc(?{print \"Hi Mom!\";})def/; # matches,\n# prints 'Hi Mom!'\n$x =~ /aaa(?{print \"Hi Mom!\";})def/; # doesn't match,\n# no 'Hi Mom!'\n\nPay careful attention to the next example:\n\n$x =~ /abc(?{print \"Hi Mom!\";})ddd/; # doesn't match,\n# no 'Hi Mom!'\n# but why not?\n\nAt first glance, you'd think that it shouldn't print, because obviously the \"ddd\" isn't going\nto match the target string. But look at this example:\n\n$x =~ /abc(?{print \"Hi Mom!\";})[dD]dd/; # doesn't match,\n# but does print\n\nHmm. What happened here? If you've been following along, you know that the above pattern\nshould be effectively (almost) the same as the last one; enclosing the 'd' in a character\nclass isn't going to change what it matches. So why does the first not print while the second\none does?\n\nThe answer lies in the optimizations the regexp engine makes. In the first case, all the\nengine sees are plain old characters (aside from the \"?{}\" construct). It's smart enough to\nrealize that the string 'ddd' doesn't occur in our target string before actually running the\npattern through. But in the second case, we've tricked it into thinking that our pattern is\nmore complicated. It takes a look, sees our character class, and decides that it will have to\nactually run the pattern to determine whether or not it matches, and in the process of\nrunning it hits the print statement before it discovers that we don't have a match.\n\nTo take a closer look at how the engine does optimizations, see the section \"Pragmas and\ndebugging\" below.\n\nMore fun with \"?{}\":\n\n$x =~ /(?{print \"Hi Mom!\";})/;         # matches,\n# prints 'Hi Mom!'\n$x =~ /(?{$c = 1;})(?{print \"$c\";})/;  # matches,\n# prints '1'\n$x =~ /(?{$c = 1;})(?{print \"$^R\";})/; # matches,\n# prints '1'\n\nThe bit of magic mentioned in the section title occurs when the regexp backtracks in the\nprocess of searching for a match.  If the regexp backtracks over a code expression and if the\nvariables used within are localized using \"local\", the changes in the variables produced by\nthe code expression are undone! Thus, if we wanted to count how many times a character got\nmatched inside a group, we could use, e.g.,\n\n$x = \"aaaa\";\n$count = 0;  # initialize 'a' count\n$c = \"bob\";  # test if $c gets clobbered\n$x =~ /(?{local $c = 0;})         # initialize count\n( a                        # match 'a'\n(?{local $c = $c + 1;})  # increment count\n)*                         # do this any number of times,\naa                         # but match 'aa' at the end\n(?{$count = $c;})          # copy local $c var into $count\n/x;\nprint \"'a' count is $count, \\$c variable is '$c'\\n\";\n\nThis prints\n\n'a' count is 2, $c variable is 'bob'\n\nIf we replace the \" (?{local $c = $c + 1;})\" with \" (?{$c = $c + 1;})\", the variable changes\nare not undone during backtracking, and we get\n\n'a' count is 4, $c variable is 'bob'\n\nNote that only localized variable changes are undone.  Other side effects of code expression\nexecution are permanent.  Thus\n\n$x = \"aaaa\";\n$x =~ /(a(?{print \"Yow\\n\";}))*aa/;\n\nproduces\n\nYow\nYow\nYow\nYow\n\nThe result $^R is automatically localized, so that it will behave properly in the presence of\nbacktracking.\n\nThis example uses a code expression in a conditional to match a definite article, either\n'the' in English or 'der|die|das' in German:\n\n$lang = 'DE';  # use German\n...\n$text = \"das\";\nprint \"matched\\n\"\nif $text =~ /(?(?{\n$lang eq 'EN'; # is the language English?\n})\nthe |             # if so, then match 'the'\n(der|die|das)     # else, match 'der|die|das'\n)\n/xi;\n\nNote that the syntax here is \"(?(?{...})yes-regexp|no-regexp)\", not\n\"(?((?{...}))yes-regexp|no-regexp)\".  In other words, in the case of a code expression, we\ndon't need the extra parentheses around the conditional.\n\nIf you try to use code expressions where the code text is contained within an interpolated\nvariable, rather than appearing literally in the pattern, Perl may surprise you:\n\n$bar = 5;\n$pat = '(?{ 1 })';\n/foo(?{ $bar })bar/; # compiles ok, $bar not interpolated\n/foo(?{ 1 })$bar/;   # compiles ok, $bar interpolated\n/foo${pat}bar/;      # compile error!\n\n$pat = qr/(?{ $foo = 1 })/;  # precompile code regexp\n/foo${pat}bar/;      # compiles ok\n\nIf a regexp has a variable that interpolates a code expression, Perl treats the regexp as an\nerror. If the code expression is precompiled into a variable, however, interpolating is ok.\nThe question is, why is this an error?\n\nThe reason is that variable interpolation and code expressions together pose a security risk.\nThe combination is dangerous because many programmers who write search engines often take\nuser input and plug it directly into a regexp:\n\n$regexp = <>;       # read user-supplied regexp\n$chomp $regexp;     # get rid of possible newline\n$text =~ /$regexp/; # search $text for the $regexp\n\nIf the $regexp variable contains a code expression, the user could then execute arbitrary\nPerl code.  For instance, some joker could search for \"system('rm -rf *');\" to erase your\nfiles.  In this sense, the combination of interpolation and code expressions taints your\nregexp.  So by default, using both interpolation and code expressions in the same regexp is\nnot allowed.  If you're not concerned about malicious users, it is possible to bypass this\nsecurity check by invoking \"use re 'eval'\":\n\nuse re 'eval';       # throw caution out the door\n$bar = 5;\n$pat = '(?{ 1 })';\n/foo${pat}bar/;      # compiles ok\n\nAnother form of code expression is the pattern code expression.  The pattern code expression\nis like a regular code expression, except that the result of the code evaluation is treated\nas a regular expression and matched immediately.  A simple example is\n\n$length = 5;\n$char = 'a';\n$x = 'aaaaabb';\n$x =~ /(??{$char x $length})/x; # matches, there are 5 of 'a'\n\nThis final example contains both ordinary and pattern code expressions.  It detects whether a\nbinary string 1101010010001... has a Fibonacci spacing 0,1,1,2,3,5,...  of the '1''s:\n\n$x = \"1101010010001000001\";\n$z0 = ''; $z1 = '0';   # initial conditions\nprint \"It is a Fibonacci sequence\\n\"\nif $x =~ /^1         # match an initial '1'\n(?:\n((??{ $z0 })) # match some '0'\n1             # and then a '1'\n(?{ $z0 = $z1; $z1 .= $^N; })\n)+   # repeat as needed\n$      # that is all there is\n/x;\nprintf \"Largest sequence matched was %d\\n\", length($z1)-length($z0);\n\nRemember that $^N is set to whatever was matched by the last completed capture group. This\nprints\n\nIt is a Fibonacci sequence\nLargest sequence matched was 5\n\nHa! Try that with your garden variety regexp package...\n\nNote that the variables $z0 and $z1 are not substituted when the regexp is compiled, as\nhappens for ordinary variables outside a code expression.  Rather, the whole code block is\nparsed as perl code at the same time as perl is compiling the code containing the literal\nregexp pattern.\n\nThis regexp without the \"/x\" modifier is\n\n/^1(?:((??{ $z0 }))1(?{ $z0 = $z1; $z1 .= $^N; }))+$/\n\nwhich shows that spaces are still possible in the code parts. Nevertheless, when working with\ncode and conditional expressions, the extended form of regexps is almost necessary in\ncreating and debugging regexps.\n"
                    },
                    {
                        "name": "Backtracking control verbs",
                        "content": "Perl 5.10 introduced a number of control verbs intended to provide detailed control over the\nbacktracking process, by directly influencing the regexp engine and by providing monitoring\ntechniques.  See \"Special Backtracking Control Verbs\" in perlre for a detailed description.\n\nBelow is just one example, illustrating the control verb \"(*FAIL)\", which may be abbreviated\nas \"(*F)\". If this is inserted in a regexp it will cause it to fail, just as it would at some\nmismatch between the pattern and the string. Processing of the regexp continues as it would\nafter any \"normal\" failure, so that, for instance, the next position in the string or another\nalternative will be tried. As failing to match doesn't preserve capture groups or produce\nresults, it may be necessary to use this in combination with embedded code.\n\n%count = ();\n\"supercalifragilisticexpialidocious\" =~\n/([aeiou])(?{ $count{$1}++; })(*FAIL)/i;\nprintf \"%3d '%s'\\n\", $count{$}, $ for (sort keys %count);\n\nThe pattern begins with a class matching a subset of letters.  Whenever this matches, a\nstatement like \"$count{'a'}++;\" is executed, incrementing the letter's counter. Then\n\"(*FAIL)\" does what it says, and the regexp engine proceeds according to the book: as long as\nthe end of the string hasn't been reached, the position is advanced before looking for\nanother vowel. Thus, match or no match makes no difference, and the regexp engine proceeds\nuntil the entire string has been inspected.  (It's remarkable that an alternative solution\nusing something like\n\n$count{lc($)}++ for split('', \"supercalifragilisticexpialidocious\");\nprintf \"%3d '%s'\\n\", $count2{$}, $ for ( qw{ a e i o u } );\n\nis considerably slower.)\n"
                    },
                    {
                        "name": "Pragmas and debugging",
                        "content": "Speaking of debugging, there are several pragmas available to control and debug regexps in\nPerl.  We have already encountered one pragma in the previous section, \"use re 'eval';\", that\nallows variable interpolation and code expressions to coexist in a regexp.  The other pragmas\nare\n\nuse re 'taint';\n$tainted = <>;\n@parts = ($tainted =~ /(\\w+)\\s+(\\w+)/; # @parts is now tainted\n\nThe \"taint\" pragma causes any substrings from a match with a tainted variable to be tainted\nas well.  This is not normally the case, as regexps are often used to extract the safe bits\nfrom a tainted variable.  Use \"taint\" when you are not extracting safe bits, but are\nperforming some other processing.  Both \"taint\" and \"eval\" pragmas are lexically scoped,\nwhich means they are in effect only until the end of the block enclosing the pragmas.\n\nuse re '/m';  # or any other flags\n$multilinestring =~ /^foo/; # /m is implied\n\nThe \"re '/flags'\" pragma (introduced in Perl 5.14) turns on the given regular expression\nflags until the end of the lexical scope.  See \"'/flags' mode\" in re for more detail.\n\nuse re 'debug';\n/^(.*)$/s;       # output debugging info\n\nuse re 'debugcolor';\n/^(.*)$/s;       # output debugging info in living color\n\nThe global \"debug\" and \"debugcolor\" pragmas allow one to get detailed debugging info about\nregexp compilation and execution.  \"debugcolor\" is the same as debug, except the debugging\ninformation is displayed in color on terminals that can display termcap color sequences.\nHere is example output:\n\n% perl -e 'use re \"debug\"; \"abc\" =~ /a*b+c/;'\nCompiling REx 'a*b+c'\nsize 9 first at 1\n1: STAR(4)\n2:   EXACT <a>(0)\n4: PLUS(7)\n5:   EXACT <b>(0)\n7: EXACT <c>(9)\n9: END(0)\nfloating 'bc' at 0..2147483647 (checking floating) minlen 2\nGuessing start of match, REx 'a*b+c' against 'abc'...\nFound floating substr 'bc' at offset 1...\nGuessed: match at offset 0\nMatching REx 'a*b+c' against 'abc'\nSetting an EVAL scope, savestack=3\n0 <> <abc>           |  1:  STAR\nEXACT <a> can match 1 times out of 32767...\nSetting an EVAL scope, savestack=3\n1 <a> <bc>           |  4:    PLUS\nEXACT <b> can match 1 times out of 32767...\nSetting an EVAL scope, savestack=3\n2 <ab> <c>           |  7:      EXACT <c>\n3 <abc> <>           |  9:      END\nMatch successful!\nFreeing REx: 'a*b+c'\n\nIf you have gotten this far into the tutorial, you can probably guess what the different\nparts of the debugging output tell you.  The first part\n\nCompiling REx 'a*b+c'\nsize 9 first at 1\n1: STAR(4)\n2:   EXACT <a>(0)\n4: PLUS(7)\n5:   EXACT <b>(0)\n7: EXACT <c>(9)\n9: END(0)\n\ndescribes the compilation stage.  STAR(4) means that there is a starred object, in this case\n'a', and if it matches, goto line 4, i.e., PLUS(7).  The middle lines describe some\nheuristics and optimizations performed before a match:\n\nfloating 'bc' at 0..2147483647 (checking floating) minlen 2\nGuessing start of match, REx 'a*b+c' against 'abc'...\nFound floating substr 'bc' at offset 1...\nGuessed: match at offset 0\n\nThen the match is executed and the remaining lines describe the process:\n\nMatching REx 'a*b+c' against 'abc'\nSetting an EVAL scope, savestack=3\n0 <> <abc>           |  1:  STAR\nEXACT <a> can match 1 times out of 32767...\nSetting an EVAL scope, savestack=3\n1 <a> <bc>           |  4:    PLUS\nEXACT <b> can match 1 times out of 32767...\nSetting an EVAL scope, savestack=3\n2 <ab> <c>           |  7:      EXACT <c>\n3 <abc> <>           |  9:      END\nMatch successful!\nFreeing REx: 'a*b+c'\n\nEach step is of the form \"n <x> <y>\", with \"<x>\" the part of the string matched and \"<y>\" the\npart not yet matched.  The \"|  1:  STAR\" says that Perl is at line number 1 in the\ncompilation list above.  See \"Debugging Regular Expressions\" in perldebguts for much more\ndetail.\n\nAn alternative method of debugging regexps is to embed \"print\" statements within the regexp.\nThis provides a blow-by-blow account of the backtracking in an alternation:\n\n\"that this\" =~ m@(?{print \"Start at position \", pos, \"\\n\";})\nt(?{print \"t1\\n\";})\nh(?{print \"h1\\n\";})\ni(?{print \"i1\\n\";})\ns(?{print \"s1\\n\";})\n|\nt(?{print \"t2\\n\";})\nh(?{print \"h2\\n\";})\na(?{print \"a2\\n\";})\nt(?{print \"t2\\n\";})\n(?{print \"Done at position \", pos, \"\\n\";})\n@x;\n\nprints\n\nStart at position 0\nt1\nh1\nt2\nh2\na2\nt2\nDone at position 4\n"
                    }
                ]
            },
            "SEE ALSO": {
                "content": "This is just a tutorial.  For the full story on Perl regular expressions, see the perlre\nregular expressions reference page.\n\nFor more information on the matching \"m//\" and substitution \"s///\" operators, see \"Regexp\nQuote-Like Operators\" in perlop.  For information on the \"split\" operation, see \"split\" in\nperlfunc.\n\nFor an excellent all-around resource on the care and feeding of regular expressions, see the\nbook Mastering Regular Expressions by Jeffrey Friedl (published by O'Reilly, ISBN\n1556592-257-3).\n",
                "subsections": []
            },
            "AUTHOR AND COPYRIGHT": {
                "content": "Copyright (c) 2000 Mark Kvale.  All rights reserved.  Now maintained by Perl porters.\n\nThis document may be distributed under the same terms as Perl itself.\n",
                "subsections": [
                    {
                        "name": "Acknowledgments",
                        "content": "The inspiration for the stop codon DNA example came from the ZIP code example in chapter 7 of\nMastering Regular Expressions.\n\nThe author would like to thank Jeff Pinyan, Andrew Johnson, Peter Haworth, Ronald J Kimball,\nand Joe Smith for all their helpful comments.\n\n\n\nperl v5.34.0                                 2025-07-25                                 PERLRETUT(1)"
                    }
                ]
            }
        }
    }
}