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.
Update: added /s in the while condition.
Update: This other discussion led to a much better solution, so I commented out the original code.
#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 && $n++; # a capturing (, count it! # } # $n; #} sub captures { ( @_ = '' =~ /(@{[shift]})??/ ) - 1; }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Count capturing parentheses in a compiled regexp
by hv (Prior) on May 02, 2004 at 12:12 UTC | |
by BooK (Curate) on May 02, 2004 at 15:20 UTC | |
Re: Count capturing parentheses in a compiled regexp
by japhy (Canon) on May 02, 2004 at 16:03 UTC | |
Re: Count capturing parentheses in a compiled regexp
by japhy (Canon) on Jun 27, 2004 at 03:35 UTC |
Back to
Cool Uses for Perl