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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |