<?xml version="1.0" encoding="windows-1252"?>
<node id="349794" title="Count capturing parentheses in a compiled regexp" created="2004-05-02 06:28:13" updated="2005-08-03 12:31:36">
<type id="1980">
snippet</type>
<author id="21732">
BooK</author>
<data>
<field name="doctext">
</field>
<field name="snippetdesc">
&lt;p&gt;This subroutines count the number of capturing parentheses in a compiled regular expression. Since the regexp is compiled, we know it's correct, and thus we only have to count the opening parentheses.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Update:&lt;/b&gt; added &lt;tt&gt;/s&lt;/tt&gt; in the while condition.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Update:&lt;/b&gt; [id://349891|This other discussion] led to
a much better solution, so I commented out the original code.&lt;/p&gt;</field>
<field name="snippetcode">
&lt;CODE&gt;
#sub captures {
#    local $_ = shift;
#    croak "$_ is not a compiled regexp" unless ref eq 'Regexp';
#    my $n = 0;
#    while( /\G(?=.)/gcs ) {
#      /\G[^\\(]*/gc;     # ignore uninteresting stuff
#      /\G(?:\\.)*/gc;    # ignore backslashed stuff
#      /\G\(\?/gc;        # ignore special regexps
#      /\G\(/gc &amp;&amp; $n++;  # a capturing (, count it!
#    }
#    $n;
#}

sub captures { ( @_ = '' =~ /(@{[shift]})??/ ) - 1; }

&lt;/CODE&gt;</field>
</data>
</node>
