{
    "mode": "man",
    "parameter": "perlreguts",
    "section": "1",
    "url": "https://www.chedong.com/phpMan.php/man/perlreguts/1/json",
    "generated": "2026-12-06T23:53:15Z",
    "sections": {
        "NAME": {
            "content": "perlreguts - Description of the Perl regular expression engine.\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "This document is an attempt to shine some light on the guts of the regex engine and how it\nworks. The regex engine represents a significant chunk of the perl codebase, but is\nrelatively poorly understood. This document is a meagre attempt at addressing this situation.\nIt is derived from the author's experience, comments in the source code, other papers on the\nregex engine, feedback on the perl5-porters mail list, and no doubt other places as well.\n\nNOTICE! It should be clearly understood that the behavior and structures discussed in this\nrepresents the state of the engine as the author understood it at the time of writing. It is\nNOT an API definition, it is purely an internals guide for those who want to hack the regex\nengine, or understand how the regex engine works. Readers of this document are expected to\nunderstand perl's regex syntax and its usage in detail. If you want to learn about the basics\nof Perl's regular expressions, see perlre. And if you want to replace the regex engine with\nyour own, see perlreapi.\n",
            "subsections": []
        },
        "OVERVIEW": {
            "content": "",
            "subsections": [
                {
                    "name": "A quick note on terms",
                    "content": "There is some debate as to whether to say \"regexp\" or \"regex\". In this document we will use\nthe term \"regex\" unless there is a special reason not to, in which case we will explain why.\n\nWhen speaking about regexes we need to distinguish between their source code form and their\ninternal form. In this document we will use the term \"pattern\" when we speak of their\ntextual, source code form, and the term \"program\" when we speak of their internal\nrepresentation. These correspond to the terms S-regex and B-regex that Mark Jason Dominus\nemploys in his paper on \"Rx\" ([1] in \"REFERENCES\").\n"
                },
                {
                    "name": "What is a regular expression engine?",
                    "content": "A regular expression engine is a program that takes a set of constraints specified in a mini-\nlanguage, and then applies those constraints to a target string, and determines whether or\nnot the string satisfies the constraints. See perlre for a full definition of the language.\n\nIn less grandiose terms, the first part of the job is to turn a pattern into something the\ncomputer can efficiently use to find the matching point in the string, and the second part is\nperforming the search itself.\n\nTo do this we need to produce a program by parsing the text. We then need to execute the\nprogram to find the point in the string that matches. And we need to do the whole thing\nefficiently.\n"
                },
                {
                    "name": "Structure of a Regexp Program",
                    "content": "High Level\n\nAlthough it is a bit confusing and some people object to the terminology, it is worth taking\na look at a comment that has been in regexp.h for years:\n\nThis is essentially a linear encoding of a nondeterministic finite-state machine (aka syntax\ncharts or \"railroad normal form\" in parsing technology).\n\nThe term \"railroad normal form\" is a bit esoteric, with \"syntax diagram/charts\", or \"railroad\ndiagram/charts\" being more common terms.  Nevertheless it provides a useful mental image of a\nregex program: each node can be thought of as a unit of track, with a single entry and in\nmost cases a single exit point (there are pieces of track that fork, but statistically not\nmany), and the whole forms a layout with a single entry and single exit point. The matching\nprocess can be thought of as a car that moves along the track, with the particular route\nthrough the system being determined by the character read at each possible connector point. A\ncar can fall off the track at any point but it may only proceed as long as it matches the\ntrack.\n\nThus the pattern \"/foo(?:\\w+|\\d+|\\s+)bar/\" can be thought of as the following chart:\n\n[start]\n|\n<foo>\n|\n+-----+-----+\n|     |     |\n<\\w+> <\\d+> <\\s+>\n|     |     |\n+-----+-----+\n|\n<bar>\n|\n[end]\n\nThe truth of the matter is that perl's regular expressions these days are much more complex\nthan this kind of structure, but visualising it this way can help when trying to get your\nbearings, and it matches the current implementation pretty closely.\n\nTo be more precise, we will say that a regex program is an encoding of a graph. Each node in\nthe graph corresponds to part of the original regex pattern, such as a literal string or a\nbranch, and has a pointer to the nodes representing the next component to be matched. Since\n\"node\" and \"opcode\" already have other meanings in the perl source, we will call the nodes in\na regex program \"regops\".\n\nThe program is represented by an array of \"regnode\" structures, one or more of which\nrepresent a single regop of the program. Struct \"regnode\" is the smallest struct needed, and\nhas a field structure which is shared with all the other larger structures.  (Outside this\ndocument, the term \"regnode\" is sometimes used to mean \"regop\", which could be confusing.)\n\nThe \"next\" pointers of all regops except \"BRANCH\" implement concatenation; a \"next\" pointer\nwith a \"BRANCH\" on both ends of it is connecting two alternatives.  [Here we have one of the\nsubtle syntax dependencies: an individual \"BRANCH\" (as opposed to a collection of them) is\nnever concatenated with anything because of operator precedence.]\n\nThe operand of some types of regop is a literal string; for others, it is a regop leading\ninto a sub-program.  In particular, the operand of a \"BRANCH\" node is the first regop of the\nbranch.\n\nNOTE: As the railroad metaphor suggests, this is not a tree structure:  the tail of the\nbranch connects to the thing following the set of \"BRANCH\"es.  It is a like a single line of\nrailway track that splits as it goes into a station or railway yard and rejoins as it comes\nout the other side.\n\nRegops\n\nThe base structure of a regop is defined in regexp.h as follows:\n\nstruct regnode {\nU8  flags;    /* Various purposes, sometimes overridden */\nU8  type;     /* Opcode value as specified by regnodes.h */\nU16 nextoff; /* Offset in size regnode */\n};\n\nOther larger \"regnode\"-like structures are defined in regcomp.h. They are almost like\nsubclasses in that they have the same fields as \"regnode\", with possibly additional fields\nfollowing in the structure, and in some cases the specific meaning (and name) of some of base\nfields are overridden. The following is a more complete description.\n\n\"regnode1\"\n\"regnode2\"\n\"regnode1\"  structures  have  the  same header, followed by a single four-byte argument;\n\"regnode2\" structures contain two two-byte arguments instead:\n\nregnode1                U32 arg1;\nregnode2                U16 arg1;  U16 arg2;\n\n\"regnodestring\"\n\"regnodestring\" structures, used for literal strings, follow the header with a  one-byte\nlength  and  then  the string data. Strings are padded on the tail end with zero bytes so\nthat the total length of the node is a multiple of four bytes:\n\nregnodestring           char string[1];\nU8 strlen; /* overrides flags */\n\n\"regnodecharclass\"\nBracketed character classes are represented by \"regnodecharclass\" structures, which have\na four-byte argument and then a 32-byte (256-bit) bitmap indicating which  characters  in\nthe Latin1 range are included in the class.\n\nregnodecharclass        U32 arg1;\nchar bitmap[ANYOFBITMAPSIZE];\n\nVarious  flags  whose  names  begin with \"ANYOF\" are used for special situations.  Above\nLatin1 matches and things not  known  until  run-time  are  stored  in  \"Perl's  pprivate\nstructure\".\n\n\"regnodecharclassposixl\"\nThere  is  also  a  larger  form  of  a char class structure used to represent POSIX char\nclasses under \"/l\" matching, called \"regnodecharclassposixl\" which  has  an  additional\n32-bit bitmap indicating which POSIX char classes have been included.\n\nregnodecharclassposixl U32 arg1;\nchar bitmap[ANYOFBITMAPSIZE];\nU32 classflags;\n\nregnodes.h defines an array called \"PLregnodearglen[]\" which gives the size of each opcode\nin units of \"size regnode\" (4-byte). A macro is used to calculate the size of an \"EXACT\" node\nbased on its \"strlen\" field.\n\nThe  regops  are  defined  in  regnodes.h  which is generated from regcomp.sym by regcomp.pl.\nCurrently the maximum possible number of distinct regops is restricted to 256, with  about  a\nquarter already used.\n\nA  set  of  macros makes accessing the fields easier and more consistent. These include OP(),\nwhich is used to determine the type of a \"regnode\"-like structure; NEXTOFF(), which  is  the\noffset  to  the  next  node  (more  on  this  later);  ARG(),  ARG1(), ARG2(), ARGSET(), and\nequivalents for reading and setting the arguments; and STRLEN(), STRING() and OPERAND()  for\nmanipulating strings and regop bearing types.\n\nWhat regnode is next?\n\nThere are two distinct concepts of \"next regnode\" in the regex engine, and it is important to\nkeep  them  distinct  in your thinking as they overlap conceptually in many places, but where\nthey don't overlap the difference is critical. For the majority  of  regnode  types  the  two\nconcepts  are (nearly) identical in practice. The two types are \"REGNODEAFTER\" which is used\nheavily during compilation but only occasionally during execution and \"regnext\" which is used\nheavily during execution, and only occasionally during compilation.\n\n\"REGNODEAFTER\"\nThis is the \"positionally next regnode\" in the compiled regex program.  For  the  smaller\nregnode  types  it  is  \"regnodeptr+1\" under the hood, but as regnode sizes vary and can\nchange over time we offer macros which hide the gory details.\n\nIt is heavily used in the compiler phase but is only used by a few select  regnode  types\nin  the  execution  phase.  It  is  also  heavily used in the code for dumping the regexp\nprogram for debugging.\n\nThere are a selection of macros which can be used  to  compute  this  as  efficiently  as\npossible depending on the circumstances. The canonical macro is REGNODEAFTER(), which is\nthe  most  powerful  and  should  handle  any  case  we have, but is also potentially the\nslowest. There are two additional macros for the special case that you KNOW  the  current\nregnode  size  is  constant,  and  you know its type or opcode. In which case you can use\nREGNODEAFTERopcode() or REGNODEAFTERtype().\n\nIn older versions of the regex engine REGNODEAFTER() was called \"NEXTOPER\" but this  was\nfound  to  be  confusing  and it was renamed. There is also a REGNODEBEFORE(), but it is\nunsafe and should not be used in new code.\n\n\"regnext\"\nThis is the regnode which can  be  reached  by  jumping  forward  by  the  value  of  the\nNEXTOFF()  member of the regnode, or in a few cases for longer jumps by the \"arg1\" field\nof the \"regnode1\" structure. The subroutine regnext() handles this transparently. In the\nmajority of cases the \"regnext\" for a regnode is the regnode  which  should  be  executed\nafter  the  current one has successfully matched, but in some cases this may not be true.\nIn loop control and branch control  regnode  types  the  regnext  may  signify  something\nspecial,  for  BRANCH  nodes  \"regnext\" is the next BRANCH that should be executed if the\ncurrent one fails execution, and some loop control regnodes set the regnext to be the end\nof the loop so they can jump to their cleanup if the current iteration fails to match.\n\nMost regnode types do  not  create  a  branch  in  the  execution  flow,  and  leaving  aside\noptimizations  the  two  concepts  of  \"next\"  are  the same.  For instance the \"regnext\" and\n\"REGNODEAFTER\" of a SBOL opcode are the same during compilation phase. The main  place  this\nis  not  true  is  \"BRANCH\"  regnodes  where  the \"REGNODEAFTER\" represents the start of the\npattern in the branch and the \"regnext\" represents the linkage to the next BRANCH should this\none fail to match, or 0 if it is the last branch. The  looping  logic  for  quantifiers  also\nmakes  similar  use  of the distinction between the two types, with \"REGNODEAFTER\" being the\ninside of the loop construct, and the \"regnext\" pointing at the end of the loop.\n\nDuring compilation the engine may not know what the regnext is for a given  node,  so  during\ncompilation  \"regnext\"  is only used where it must be used and is known to be correct. At the\nvery end of the compilation phase we walk the regex program and correct the regnext  data  as\nappropriate,  and  also  perform various optimizations which may result in regnodes that were\nrequired during construction becoming redundant, or we may replace a  large  regnode  with  a\nmuch  smaller  one  and  filling in the gap with OPTIMIZED regnodes. Thus we might start with\nsomething like this:\n\nBRANCH\nEXACT \"foo\"\nBRANCH\nEXACT \"bar\"\nEXACT \"!\"\n\nand replace it with something like:\n\nTRIE foo|bar\nOPTIMIZED\nOPTIMIZED\nOPTIMIZED\nEXACT \"!\"\n\nthe \"REGNODEAFTER\" for the \"TRIE\" node would be an \"OPTIMIZED\" regnode, and  in  theory  the\n\"regnext\"  would  be  the same as the \"REGNODEAFTER\". But it would be inefficient to execute\nthe OPTIMIZED regnode as a noop three times, so the optimizer fixes  the  \"regnext\"  so  such\nnodes are skipped during execution phase.\n\nDuring execution phases we use the regnext() almost exclusively, and only use \"REGNODEAFTER\"\nin  special  cases where it has a well defined meaning for a given regnode type. For instance\n/x+/ results in\n\nPLUS\nEXACT \"x\"\nEND\n\nthe \"regnext\" of the \"PLUS\" regnode is the \"END\" regnode,  and  the  \"REGNODEAFTER\"  of  the\n\"PLUS\"  regnode  is  the  \"EXACT\"  regnode.  The \"regnext\" and \"REGNODEAFTER\" of the \"EXACT\"\nregnode is the \"END\" regnode.\n"
                }
            ]
        },
        "Process Overview": {
            "content": "Broadly speaking, performing a match of a string against a  pattern  involves  the  following\nsteps:\n\nA. Compilation\n1. Parsing\n2. Peep-hole optimisation and analysis\nB. Execution\n3. Start position and no-match optimisations\n4. Program execution\n\nWhere  these  steps  occur in the actual execution of a perl program is determined by whether\nthe pattern involves interpolating  any  string  variables.  If  interpolation  occurs,  then\ncompilation  happens  at  run  time. If it does not, then compilation is performed at compile\ntime. (The \"/o\" modifier changes this, as does  \"qr//\"  to  a  certain  extent.)  The  engine\ndoesn't really care that much.\n",
            "subsections": [
                {
                    "name": "Compilation",
                    "content": "This code resides primarily in regcomp.c, along with the header files regcomp.h, regexp.h and\nregnodes.h.\n\nCompilation  starts  with  pregcomp(),  which is mostly an initialisation wrapper which farms\nwork out to two other routines for the heavy lifting: the first is reg(), which is the  start\npoint for parsing; the second, studychunk(), is responsible for optimisation.\n\nInitialisation  in  pregcomp()  mostly  involves  the  creation and data-filling of a special\nstructure, \"RExCstatet\" (defined in regcomp.c).  Almost  all  internally-used  routines  in\nregcomp.h  take  a  pointer to one of these structures as their first argument, with the name\n\"pRExCstate\".  This structure is used to store  the  compilation  state  and  contains  many\nfields.  Likewise  there  are many macros which operate on this variable: anything that looks\nlike \"RExCxxxx\" is a macro that operates on this pointer/structure.\n\nreg() is the start of the parse process. It is responsible for parsing an arbitrary chunk  of\npattern up to either the end of the string, or the first closing parenthesis it encounters in\nthe  pattern.   This means it can be used to parse the top-level regex, or any section inside\nof a grouping parenthesis. It also handles the \"special parens\" that perl's regexes have. For\ninstance when parsing \"/x(?:foo)y/\", reg() will at one point be called to parse from the  \"?\"\nsymbol up to and including the \")\".\n\nAdditionally, reg() is responsible for parsing the one or more branches from the pattern, and\nfor  \"finishing  them  off\"  by  correctly  setting  their  next pointers. In order to do the\nparsing, it repeatedly calls out to regbranch(), which is responsible for handling up to  the\nfirst \"|\" symbol it sees.\n\nregbranch()  in  turn  calls  regpiece()  which handles \"things\" followed by a quantifier. In\norder to parse the \"things\", regatom() is called. This is the  lowest  level  routine,  which\nparses  out constant strings, character classes, and the various special symbols like \"$\". If\nregatom() encounters a \"(\" character it in turn calls reg().\n\nThere used to be two main passes involved in parsing, the first to calculate the size of  the\ncompiled  program,  and  the  second  to actually compile it.  But now there is only one main\npass, with an initial crude guess based  on  the  length  of  the  input  pattern,  which  is\nincreased  if  necessary  as  parsing  proceeds, and afterwards, trimmed to the actual amount\nused.\n\nHowever, it may happen  that  parsing  must  be  restarted  at  the  beginning  when  various\ncircumstances  occur  along  the  way.  An example is if the program turns out to be so large\nthat there are jumps in it that won't fit in the normal 16 bits  available.   There  are  two\nspecial  regops that can hold bigger jump destinations, BRANCHJ and LONGBRANCH.  The parse is\nrestarted, and these are used instead of the normal shorter ones.   Whenever  restarting  the\nparse  is required, the function returns failure and sets a flag as to what needs to be done.\nThis is passed up to the top level routine which takes the appropriate  action  and  restarts\nfrom scratch.  In the case of needing longer jumps, the \"RExCuseBRANCHJ\" flag is set in the\n\"RExCstatet\"  structure,  which  the  functions  know  to inspect before deciding how to do\nbranches.\n\nIn most instances, the function that discovers the issue sets the  causal  flag  and  returns\nfailure immediately.  \"Parsing complications\" contains an explicit example of how this works.\nIn  other cases, such as a forward reference to a numbered parenthetical grouping, we need to\nfinish the parse to know if that numbered grouping actually appears in the pattern.  In those\ncases, the parse is just redone at the end, with the knowledge of how many groupings occur in\nit.\n\nThe routine regtail() is called by both reg() and regbranch()  in  order  to  \"set  the  tail\npointer\"  correctly.  When  executing and we get to the end of a branch, we need to go to the\nnode following the grouping parens. When parsing, however, we don't know where the  end  will\nbe  until  we get there, so when we do we must go back and update the offsets as appropriate.\n\"regtail\" is used to make this easier.\n\nA subtlety of the parsing process means that a regex like \"/foo/\" is originally  parsed  into\nan alternation with a single branch. It is only afterwards that the optimiser converts single\nbranch alternations into the simpler form.\n\nParse Call Graph and a Grammar\n\nThe call graph looks like this:\n\nreg()                        # parse a top level regex, or inside of\n# parens\nregbranch()              # parse a single branch of an alternation\nregpiece()           # parse a pattern followed by a quantifier\nregatom()        # parse a simple pattern\nregclass()   #   used to handle a class\nreg()        #   used to handle a parenthesised\n#   subpattern\n....\n...\nregtail()            # finish off the branch\n...\nregtail()                # finish off the branch sequence. Tie each\n# branch's tail to the tail of the\n# sequence\n# (NEW) In Debug mode this is\n# regtailstudy().\n\nA grammar form might be something like this:\n\natom  : constant | class\nquant : '*' | '+' | '?' | '{min,max}'\nbranch: piece\n| piece branch\n| nothing\nbranch: branch\n| branch '|' branch\ngroup : '(' branch ')'\npiece: atom | group\npiece : piece\n| piece quant\n\nParsing complications\n\nThe implication of the above description is that a pattern containing nested parentheses will\nresult in a call graph which cycles through reg(), regbranch(), regpiece(), regatom(), reg(),\nregbranch()  etc multiple times, until the deepest level of nesting is reached. All the above\nroutines return a pointer to a \"regnode\", which is usually the  last  regnode  added  to  the\nprogram.  However,  one complication is that reg() returns NULL for parsing \"(?:)\" syntax for\nembedded modifiers, setting the flag \"TRYAGAIN\". The \"TRYAGAIN\" propagates upwards  until  it\nis  captured, in some cases by regatom(), but otherwise unconditionally by regbranch(). Hence\nit will never be returned by regbranch() to reg(). This flag permits patterns such as \"(?i)+\"\nto be detected as errors (Quantifier follows nothing in regex; marked by <-- HERE in  m/(?i)+\n<-- HERE /).\n\nAnother  complication  is that the representation used for the program differs if it needs to\nstore Unicode, but it's not always possible to know for sure whether  it  does  until  midway\nthrough  parsing. The Unicode representation for the program is larger, and cannot be matched\nas efficiently. (See \"Unicode and Localisation Support\" below for more details  as  to  why.)\nIf  the  pattern  contains  literal  Unicode,  it's  obvious  that the program needs to store\nUnicode. Otherwise, the parser optimistically assumes that the more efficient  representation\ncan  be  used,  and starts sizing on this basis.  However, if it then encounters something in\nthe pattern  which  must  be  stored  as  Unicode,  such  as  an  \"\\x{...}\"  escape  sequence\nrepresenting  a  character literal, then this means that all previously calculated sizes need\nto be redone, using values appropriate for  the  Unicode  representation.   This  is  another\ninstance  where  the  parsing needs to be restarted, and it can and is done immediately.  The\nfunction returns failure, and sets the flag \"RESTARTUTF8\" (encapsulated by using  the  macro\n\"REQUIREUTF8\").   This restart request is propagated up the call chain in a similar fashion,\nuntil it is \"caught\" in Perlreopcompile(), which marks the pattern as containing  Unicode,\nand  restarts  the  sizing  pass.  It is also possible for constructions within run-time code\nblocks  to  turn   out   to   need   Unicode   representation.,   which   is   signalled   by\nScompileruntimecode() returning false to Perlreopcompile().\n\nThe  restart  was previously implemented using a \"longjmp\" in regatom() back to a \"setjmp\" in\nPerlreopcompile(), but this proved to be problematic as the latter  is  a  large  function\ncontaining  many  automatic variables, which interact badly with the emergent control flow of\n\"setjmp\".\n\nDebug Output\n\nStarting in the 5.9.x development version of perl you can \"use re Debug =>  'PARSE'\"  to  see\nsome  trace  information about the parse process. We will start with some simple patterns and\nbuild up to more complex patterns.\n\nSo when we parse \"/foo/\" we see something like the following table. The left  shows  what  is\nbeing  parsed, and the number indicates where the next regop would go. The stuff on the right\nis the trace output of the graph. The names are chosen to be short to make it less  dense  on\nthe screen. 'tsdy' is a special form of regtail() which does some extra analysis.\n\n>foo<             1    reg\nbrnc\npiec\natom\n><                4      tsdy~ EXACT <foo> (EXACT) (1)\n~ attach to END (3) offset to 2\n\nThe resulting program then looks like:\n\n1: EXACT <foo>(3)\n3: END(0)\n\nAs  you  can  see,  even though we parsed out a branch and a piece, it was ultimately only an\natom. The final program shows us how things work. We have an \"EXACT\" regop,  followed  by  an\n\"END\"  regop.  The  number  in  parens  indicates  where  the \"regnext\" of the node goes. The\n\"regnext\" of an \"END\" regop is unused, as \"END\" regops mean we have successfully matched. The\nnumber on the left indicates the position of the regop in the regnode array.\n\nNow let's try a harder pattern. We will  add  a  quantifier,  so  now  we  have  the  pattern\n\"/foo+/\". We will see that regbranch() calls regpiece() twice.\n\n>foo+<            1    reg\nbrnc\npiec\natom\n>o+<              3        piec\natom\n><                6        tail~ EXACT <fo> (1)\n7      tsdy~ EXACT <fo> (EXACT) (1)\n~ PLUS (END) (3)\n~ attach to END (6) offset to 3\n\nAnd we end up with the program:\n\n1: EXACT <fo>(3)\n3: PLUS(6)\n4:   EXACT <o>(0)\n6: END(0)\n\nNow  we  have  a  special case. The \"EXACT\" regop has a \"regnext\" of 0. This is because if it\nmatches it should try to match itself again. The \"PLUS\" regop handles the actual  failure  of\nthe  \"EXACT\" regop and acts appropriately (going to regnode 6 if the \"EXACT\" matched at least\nonce, or failing if it didn't).\n\nNow for something much more complex: \"/x(?:foo*|b[a][rR])(foo|bar)$/\"\n\n>x(?:foo*|b...    1    reg\nbrnc\npiec\natom\n>(?:foo*|b[...    3        piec\natom\n>?:foo*|b[a...                 reg\n>foo*|b[a][...                   brnc\npiec\natom\n>o*|b[a][rR...    5                piec\natom\n>|b[a][rR])...    8                tail~ EXACT <fo> (3)\n>b[a][rR])(...    9              brnc\n10                piec\natom\n>[a][rR])(f...   12                piec\natom\n>a][rR])(fo...                         clas\n>[rR])(foo|...   14                tail~ EXACT <b> (10)\npiec\natom\n>rR])(foo|b...                         clas\n>)(foo|bar)...   25                tail~ EXACT <a> (12)\ntail~ BRANCH (3)\n26              tsdy~ BRANCH (END) (9)\n~ attach to TAIL (25) offset to 16\ntsdy~ EXACT <fo> (EXACT) (4)\n~ STAR (END) (6)\n~ attach to TAIL (25) offset to 19\ntsdy~ EXACT <b> (EXACT) (10)\n~ EXACT <a> (EXACT) (12)\n~ ANYOF[Rr] (END) (14)\n~ attach to TAIL (25) offset to 11\n>(foo|bar)$<               tail~ EXACT <x> (1)\npiec\natom\n>foo|bar)$<                    reg\n28              brnc\npiec\natom\n>|bar)$<         31              tail~ OPEN1 (26)\n>bar)$<                          brnc\n32                piec\natom\n>)$<             34              tail~ BRANCH (28)\n36              tsdy~ BRANCH (END) (31)\n~ attach to CLOSE1 (34) offset to 3\ntsdy~ EXACT <foo> (EXACT) (29)\n~ attach to CLOSE1 (34) offset to 5\ntsdy~ EXACT <bar> (EXACT) (32)\n~ attach to CLOSE1 (34) offset to 2\n>$<                        tail~ BRANCH (3)\n~ BRANCH (9)\n~ TAIL (25)\npiec\natom\n><               37        tail~ OPEN1 (26)\n~ BRANCH (28)\n~ BRANCH (31)\n~ CLOSE1 (34)\n38      tsdy~ EXACT <x> (EXACT) (1)\n~ BRANCH (END) (3)\n~ BRANCH (END) (9)\n~ TAIL (END) (25)\n~ OPEN1 (END) (26)\n~ BRANCH (END) (28)\n~ BRANCH (END) (31)\n~ CLOSE1 (END) (34)\n~ EOL (END) (36)\n~ attach to END (37) offset to 1\n\nResulting in the program\n\n1: EXACT <x>(3)\n3: BRANCH(9)\n4:   EXACT <fo>(6)\n6:   STAR(26)\n7:     EXACT <o>(0)\n9: BRANCH(25)\n10:   EXACT <ba>(14)\n12:   OPTIMIZED (2 nodes)\n14:   ANYOF[Rr](26)\n25: TAIL(26)\n26: OPEN1(28)\n28:   TRIE-EXACT(34)\n[StS:1 Wds:2 Cs:6 Uq:5 #Sts:7 Mn:3 Mx:3 Stcls:bf]\n<foo>\n<bar>\n30:   OPTIMIZED (4 nodes)\n34: CLOSE1(36)\n36: EOL(37)\n37: END(0)\n\nHere we can see a much more complex program, with various optimisations in play.  At  regnode\n10 we see an example where a character class with only one character in it was turned into an\n\"EXACT\"  node.  We  can  also  see where an entire alternation was turned into a \"TRIE-EXACT\"\nnode. As a consequence, some of the regnodes have been marked as optimised away. We  can  see\nthat  the  \"$\"  symbol  has  been converted into an \"EOL\" regop, a special piece of code that\nlooks for \"\\n\" or the end of the string.\n\nThe next pointer for \"BRANCH\"es is interesting in that it points at where execution should go\nif the branch fails. When executing, if the engine tries to  traverse  from  a  branch  to  a\n\"regnext\"  that  isn't a branch then the engine will know that the entire set of branches has\nfailed.\n\nPeep-hole Optimisation and Analysis\n\nThe regular expression engine can be a weighty tool to wield. On  long  strings  and  complex\npatterns  it  can  end up having to do a lot of work to find a match, and even more to decide\nthat no match is possible.  Consider a situation like the following pattern.\n\n'ababababababababababab' =~ /(a|b)*z/\n\nThe \"(a|b)*\" part can match at every char in the string, and then  fail  every  time  because\nthere  is no \"z\" in the string. So obviously we can avoid using the regex engine unless there\nis a \"z\" in the string.  Likewise in a pattern like:\n\n/foo(\\w+)bar/\n\nIn this case we know that the string must contain a \"foo\" which must be followed by \"bar\". We\ncan use Fast Boyer-Moore matching as implemented in fbminstr() to find the location of these\nstrings. If they don't exist then we don't need to resort to the much  more  expensive  regex\nengine.   Even  better, if they do exist then we can use their positions to reduce the search\nspace that the regex engine needs to cover to determine if the entire pattern matches.\n\nThere are various aspects of the pattern that can be used to facilitate  optimisations  along\nthese lines:\n\n•    anchored fixed strings\n\n•    floating fixed strings\n\n•    minimum and maximum length requirements\n\n•    start class\n\n•    Beginning/End of line positions\n\nAnother form of optimisation that can occur is the post-parse \"peep-hole\" optimisation, where\ninefficient constructs are replaced by more efficient constructs. The \"TAIL\" regops which are\nused  during  parsing to mark the end of branches and the end of groups are examples of this.\nThese regops are used as place-holders during construction and \"always match\" so they can  be\n\"optimised away\" by making the things that point to the \"TAIL\" point to the thing that \"TAIL\"\npoints to, thus \"skipping\" the node.\n\nAnother  optimisation  that  can  occur  is  that  of  \"\"EXACT\"  merging\"  which is where two\nconsecutive \"EXACT\" nodes are merged into a single regop. An even  more  aggressive  form  of\nthis  is  that a branch sequence of the form \"EXACT BRANCH ... EXACT\" can be converted into a\n\"TRIE-EXACT\" regop.\n\nAll of this occurs in the routine studychunk() which uses a special structure  \"scandatat\"\nto  store  the  analysis  that it has performed, and does the \"peep-hole\" optimisations as it\ngoes.\n\nThe code involved in studychunk() is extremely cryptic. Be careful. :-)\n"
                },
                {
                    "name": "Execution",
                    "content": "Execution of a regex generally involves two phases, the first being finding the  start  point\nin the string where we should match from, and the second being running the regop interpreter.\n\nIf  we  can  tell  that  there  is  no  valid  start  point  then we don't bother running the\ninterpreter at all. Likewise, if we know from the analysis phase  that  we  cannot  detect  a\nshort-cut to the start position, we go straight to the interpreter.\n\nThe  two  entry  points  are reintuitstart() and pregexec(). These routines have a somewhat\nincestuous relationship with overlap between their functions, and pregexec()  may  even  call\nreintuitstart()  on its own. Nevertheless other parts of the perl source code may call into\neither, or both.\n\nExecution of the interpreter itself used to be recursive, but thanks to the efforts  of  Dave\nMitchell  in  the  5.9.x  development  track,  that  has  changed:  now  an internal stack is\nmaintained on the heap and the routine is fully iterative. This can make  it  tricky  as  the\ncode  is  quite conservative about what state it stores, with the result that two consecutive\nlines in the code can actually be running in totally different contexts due to the  simulated\nrecursion.\n\nStart position and no-match optimisations\n\nreintuitstart()  is  responsible  for  handling  start points and no-match optimisations as\ndetermined by the results of the analysis done by studychunk() (and described in  \"Peep-hole\nOptimisation and Analysis\").\n\nThe  basic  structure of this routine is to try to find the start- and/or end-points of where\nthe pattern could match, and to ensure that the string is long enough to match  the  pattern.\nIt  tries  to  use  more  efficient  methods  over  less  efficient  methods  and may involve\nconsiderable cross-checking of constraints to find the place in the string that matches.  For\ninstance it may try to determine that a given fixed string must be not  only  present  but  a\ncertain number of chars before the end of the string, or whatever.\n\nIt calls several other routines, such as fbminstr() which does Fast Boyer Moore matching and\nfindbyclass()  which is responsible for finding the start using the first mandatory regop in\nthe program.\n\nWhen the optimisation criteria have been satisfied, regtry() is called to perform the match.\n\nProgram execution\n\npregexec() is the main entry point for running a regex. It contains support for  initialising\nthe  regex  interpreter's  state,  running  reintuitstart()  if  needed,  and  running  the\ninterpreter on the string from various start positions as needed. When it is necessary to use\nthe regex interpreter pregexec() calls regtry().\n\nregtry() is the entry point into the regex interpreter. It expects as arguments a pointer  to\na  \"regmatchinfo\"  structure and a pointer to a string.  It returns an integer 1 for success\nand a 0 for failure.  It is basically a set-up wrapper around regmatch().\n\n\"regmatch\" is the main \"recursive loop\" of the interpreter. It is basically  a  giant  switch\nstatement  that  implements  a  state  machine,  where  the  possible  states  are the regops\nthemselves, plus a number of additional intermediate and failure states. A few of the  states\nare implemented as subroutines but the bulk are inline code.\n"
                }
            ]
        },
        "MISCELLANEOUS": {
            "content": "",
            "subsections": [
                {
                    "name": "Unicode and Localisation Support",
                    "content": "When dealing with strings containing characters that cannot be represented using an eight-bit\ncharacter set, perl uses an internal representation that is a permissive version of Unicode's\nUTF-8  encoding[2].  This  uses single bytes to represent characters from the ASCII character\nset, and sequences of two or more bytes for all other characters. (See  perlunitut  for  more\ninformation  about  the  relationship between UTF-8 and perl's encoding, utf8. The difference\nisn't important for this discussion.)\n\nNo matter how you look at it, Unicode support is going to be a pain in a regex engine. Tricks\nthat might be fine when you have 256 possible characters often won't scale to handle the size\nof the UTF-8 character set.  Things you can take for granted with ASCII may not be true  with\nUnicode.  For instance, in ASCII, it is safe to assume that \"sizeof(char1) == sizeof(char2)\",\nbut in UTF-8 it isn't. Unicode case folding is vastly more complex than the simple  rules  of\nASCII,  and  even when not using Unicode but only localised single byte encodings, things can\nget tricky (for example, LATIN SMALL  LETTER  SHARP  S  (U+00DF,  ß)  should  match  'SS'  in\nlocalised case-insensitive matching).\n\nMaking things worse is that UTF-8 support was a later addition to the regex engine (as it was\nto  perl) and this necessarily  made things a lot more complicated. Obviously it is easier to\ndesign a regex engine with Unicode support in mind from the beginning than it is to  retrofit\nit to one that wasn't.\n\nNearly all regops that involve looking at the input string have two cases, one for UTF-8, and\none not. In fact, it's often more complex than that, as the pattern may be UTF-8 as well.\n\nCare  must  be taken when making changes to make sure that you handle UTF-8 properly, both at\ncompile time and at execution time, including when the string and pattern are mismatched.\n"
                },
                {
                    "name": "Base Structures",
                    "content": "The \"regexp\" structure described in perlreapi is common to all  regex  engines.  Two  of  its\nfields  are intended for the private use of the regex engine that compiled the pattern. These\nare the \"intflags\" and pprivate members. The \"pprivate\" is a void  pointer  to  an  arbitrary\nstructure  whose  use and management is the responsibility of the compiling engine. perl will\nnever modify either of these values. In the case of the stock engine the structure pointed to\nby \"pprivate\" is called \"regexpinternal\".\n\nIts \"pprivate\" and \"intflags\" fields contain data specific to each engine.\n\nThere are two structures used to store a compiled  regular  expression.   One,  the  \"regexp\"\nstructure  described in perlreapi is populated by the engine currently being used and some of\nits fields read by perl to implement things such as the stringification of \"qr//\".\n\nThe other structure is pointed to by the \"regexp\" struct's \"pprivate\" and is in  addition  to\n\"intflags\"  in  the  same  struct  considered  to  be  the property of the regex engine which\ncompiled the regular expression;\n\nThe regexp structure contains all the data that perl needs to be aware of  to  properly  work\nwith  the  regular  expression.  It  includes  data  about optimisations that perl can use to\ndetermine if the regex engine should really be used, and various other control info  that  is\nneeded  to  properly  execute patterns in various contexts such as is the pattern anchored in\nsome way, or what flags were used during the compile, or whether the program contains special\nconstructs that perl needs to be aware of.\n\nIn addition it contains two fields that are intended for the private use of the regex  engine\nthat compiled the pattern. These are the \"intflags\" and pprivate members. The \"pprivate\" is a\nvoid  pointer to an arbitrary structure whose use and management is the responsibility of the\ncompiling engine. perl will never modify either of these values.\n\nAs mentioned earlier, in the case of the default engines, the \"pprivate\" will be a pointer to\na regexpinternal structure which holds the compiled program and any additional data that  is\nprivate to the regex engine implementation.\n\nPerl's \"pprivate\" structure\n\nThe  following structure is used as the \"pprivate\" struct by perl's regex engine. Since it is\nspecific to perl it is only of curiosity value to other engine implementations.\n\ntypedef struct regexpinternal {\nregnode *regstclass;\nstruct regdata *data;\nstruct regcodeblocks *codeblocks;\nU32 proglen;\nU32 namelistidx;\nregnode program[1];\n} regexpinternal;\n\nDescription of the attributes is as follows:\n\n\"regstclass\"\nSpecial regop that is used by reintuitstart() to check if a pattern  can  match  at  a\ncertain  position.  For  instance  if the regex engine knows that the pattern must start\nwith a 'Z' then it can scan the string until it finds one  and  then  launch  the  regex\nengine  from  there.  The routine that handles this is called findbyclass(). Sometimes\nthis field points at a regop embedded in the program, and  sometimes  it  points  at  an\nindependent synthetic regop that has been constructed by the optimiser.\n\n\"data\"\nThis field points at a \"regdata\" structure, which is defined as follows\n\nstruct regdata {\nU32 count;\nU8 *what;\nvoid* data[1];\n};\n\nThis  structure  is  used  for  handling  data structures that the regex engine needs to\nhandle specially during a clone or free operation on the compiled product. Each  element\nin  the  data  array  has  a corresponding element in the what array. During compilation\nregops that need special structures stored will add an element to each array  using  the\nadddata() routine and then store the index in the regop.\n\nIn modern perls the 0th element of this structure is reserved and is NEVER used to store\nanything of use. This is to allow things that need to index into this array to represent\n\"no value\".\n\n\"codeblocks\"\nThis optional structure is used to manage \"(?{})\" constructs in the pattern.  It is made\nup of the following structures.\n\n/* record the position of a (?{...}) within a pattern */\nstruct regcodeblock {\nSTRLEN start;\nSTRLEN end;\nOP     *block;\nREGEXP *srcregex;\n};\n\n/* array of regcodeblock's plus header info */\nstruct regcodeblocks {\nint refcnt; /* we may be pointed to from a regex\nand from the savestack */\nint  count; /* how many code blocks */\nstruct regcodeblock *cb; /* array of regcodeblock's */\n};\n\n\"proglen\"\nStores the length of the compiled program in units of regops.\n\n\"namelistidx\"\nThis  is  the index into the data array where an AV is stored that contains the names of\nany named capture buffers in the pattern, should there be any. This is only used in  the\ndebugging version of the regex engine and when RXpPARENNAMES(prog) is true. It will be\n0 if there is no such data.\n\n\"program\"\nCompiled  program.  Inlined  into the structure so the entire struct can be treated as a\nsingle blob.\n"
                }
            ]
        },
        "SEE ALSO": {
            "content": "perlreapi\n\nperlre\n\nperlunitut\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "by Yves Orton, 2006.\n\nWith excerpts from Perl, and contributions and  suggestions  from  Ronald  J.  Kimball,  Dave\nMitchell, Dominic Dunlop, Mark Jason Dominus, Stephen McCamant, and David Landgren.\n\nNow maintained by Perl 5 Porters.\n",
            "subsections": []
        },
        "LICENCE": {
            "content": "Same terms as Perl.\n",
            "subsections": []
        },
        "REFERENCES": {
            "content": "[1] <https://perl.plover.com/Rx/paper/>\n\n[2] <https://www.unicode.org/>\n\nperl v5.38.2                                 2026-11-05                                PERLREGUTS(1)",
            "subsections": []
        }
    },
    "summary": "perlreguts - Description of the Perl regular expression engine.",
    "flags": [],
    "examples": [],
    "see_also": []
}