http://www.perlmonks.org?node_id=350042


in reply to Re: Re: Trying to count the captures in a compiled regular expression
in thread Trying to count the captures in a compiled regular expression

Upon a successful match, the match operator returns a list of the captures (or, in scalar context, the number of captures), one element for each set of capturing parentheses, even if the captured value is empty. By making the entire pattern optional, we ensure a successful match, and thus Perl will tell us how many groupings were.

As was pointed out by ysth and hugo, the case of no groupings will not return zero (because we need a true value to indicate a successful match), so we ought to put capturing parentheses around the expression, and subtract one from the result. And the possibility of embedded code, which we wouldn't want to run, is another caveat, so we want to use minimal matching. Hence:

my $regex = qr/foo/; $_ = 'anything'; my $matches = (() = /($regex)??/) - 1; # oops! fixed print "There were $matches groupings\n";

The PerlMonk tr/// Advocate
  • Comment on Explained: Trying to count the captures in a compiled regular expression
  • Download Code

Replies are listed 'Best First'.
Re: Explained: Trying to count the captures in a compiled regular expression
by ysth (Canon) on May 03, 2004 at 16:13 UTC
    That runs in scalar context, so won't work; try:
    $matches = (() = /($regex)??/) - 1;
      or even
      /$regex??/; print "There were $#+ groupings\n";

      The PerlMonk tr/// Advocate