Named groups in recursive pattern Match

361 views Asked by At

I'm matching on LaTeX-Commands of the form \command{...}{...}. The second argument is optional. My RegEx is a only slightly modificated version of one example in perl6 faq because I need to take care of the case that there may be nested LaTeX commands inside the arguments.

I want to use named groups. How can I do this? I tried to use (?<first>:...) together with (?&first), but it gives me an "infinite recursion" error. I might be a little over my head in terms of RegExes here, but this worked very nicely so far.

my $regex = qr/
          \\command
            (\{
              (?:
                [^\{\}]++
                  |
                (?1)
              )*
            \})
           (\{
              (?:
                [^\{\}]++
                  |
                (?2)
              )*
           \})?
        /x;

$s =~ m/$regex/g
1

There are 1 answers

0
Jeff Burdges On

You should be able to use named groups like s/(?<first>foo+)/\k<first>bar/ or s/(?first:foo+)/\g{first}bar/ but (?<first>:...) treats the : as part of the pattern.

I'm unsure why your (?PARNO) expressions are causing infinite recursion, but the manual has an extra paren group when doing exactly the same thing.