my $regex = qr{ ( # start of capture group 1 ... (?1) # recurse to capture group 1 ... ) # end of capture group 1 }x;

A neat feature of the  (?PARNO) extended pattern (available with Perl versions 5.10+) is that the numbering of capture groups can be made relative instead of absolute. This shines brightest when defining  qr// regex objects, which are designed to be interpolated into other  qr// m// s/// expressions. The logic of group recursion can be encapsulated and made independent of whatever other expressions go into the final regex.

In Athanasius's code above, if even one more capturing group sneaks into the  m// ahead of  $regex in the extraction expression
    my @groups = $string =~ m/$regex/g;
as in
    my @groups = $string =~ m/(x?)$regex/g;
capture group numbering is thrown off and its function is destroyed. If the absolute  (?1) group recursion in
    my $regex = qr{ (... (?1) ...) }x;
is made relative with  (?-1) then any number of extra preceding capture groups will make no difference to its function:
    my @groups = $string =~ m/(x?)(x?)(x?)$regex/g;


In reply to Re^2: how to speed up that dynamic regex? by AnomalousMonk
in thread how to speed up that dynamic regex? by rsFalse

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.