my @strings = qw( acaabbbb ); for ( @strings ) { local our $a_counter = 0; local our $b_counter = 0; / (?: a (?{ $a_counter++ }) )+ (?: b (?{ $b_counter++ }) )+ /x; print("a: $a_counter\n"); # a: 3 print("b: $b_counter\n"); # b: 4 }
If you want 2,4 instead of 3,4, you need to take backtracking into account.
my @strings = qw( acaabbbb ); for ( @strings ) { local our $a_counter = 0; local our $b_counter = 0; / (?{ # Initialize $^R { a => 0, b => 0 } }) (?: a (?{ my %h = %{$^R}; $h{a}++; +{ %h } }) )+ (?: b (?{ my %h = %{$^R}; $h{b}++; +{ %h } }) )+ (?{ # Return results my %h = %{$^R}; $a_counter = $h{a}; $b_counter = $h{b}; }) /x; print("a: $a_counter\n"); # a: 2 print("b: $b_counter\n"); # b: 4 }
In reply to Re: Extracting the number of repetitions from a regex
by ikegami
in thread Extracting the number of repetitions from a regex
by pat_mc
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |