use v5.12; use warnings; use Data::Dump; my $re_start = qr{(?\w+)\s*}; my $re_repeat = qr{\s*(?\d+)\s*}; my $str = 'a 1 2 3 b 4 5 6'; while ( $str =~ /\G$re_start/g ) { print "$+{start}: "; while ( $str =~ /\G$re_repeat/gc ) { print "$+{repeat} "; } print "\n"; } my @res; $str =~ / (?: $re_start (?{ push @res, $+{start} }) (?: $re_repeat (?{ push @res, $+{repeat} }) )* )* /gx; dd \@res;