I'm confused about what you really need, and this is quite possibly overkill. (Regex \K operator only available with Perl versions 5.10+.)
>perl -wMstrict -le
"use Test::More 'no_plan';
use Test::NoWarnings;
;;
my @vectors = (
[ 'chapters 01,02,03,04', qw(01 02 03 04), ],
[ 'chapters 1 , 2 , 3 , 4 , 5', qw(1 2 3 4 5), ],
[ 'in chapter 01', qw(01), ],
[ 'chapter 101', qw(101), ],
[ 'chapters 99, 100 ,101 also', qw(99 100 101), ],
[ 'chapters 3, 4, 5 and chapter 9', qw(3 4 5 9), ],
[ 'read chapters 3, 4 and chapter 9', qw(3 4 9), ],
'pay particular attention to the next variation',
[ 'chapters 3, 4, 5 and 9', qw(3 4 5), ],
'no chapter numbers should be extracted from any of these',
[ 'chapter' ], [ 'chapters' ], [ 'chapter ii' ], [ '01,02' ],
);
;;
VECTOR:
for my $ar_vector (@vectors) {
unless (ref $ar_vector) {
note $ar_vector;
next VECTOR;
}
my ($s, @expected) = @$ar_vector;
my @n = $s =~ m{
(?: \G (?<! \A) \s* , \s* | chapters? \s+) \K
\d+
}xmsg;
is_deeply \@n, \@expected, qq{'$s' -> (@expected)};
}
"
ok 1 - 'chapters 01,02,03,04' -> (01 02 03 04)
ok 2 - 'chapters 1 , 2 , 3 , 4 , 5' -> (1 2 3 4 5)
ok 3 - 'in chapter 01' -> (01)
ok 4 - 'chapter 101' -> (101)
ok 5 - 'chapters 99, 100 ,101 also' -> (99 100 101)
ok 6 - 'chapters 3, 4, 5 and chapter 9' -> (3 4 5 9)
ok 7 - 'read chapters 3, 4 and chapter 9' -> (3 4 9)
# pay particular attention to the next variation
ok 8 - 'chapters 3, 4, 5 and 9' -> (3 4 5)
# no chapter numbers should be extracted from any of these
ok 9 - 'chapter' -> ()
ok 10 - 'chapters' -> ()
ok 11 - 'chapter ii' -> ()
ok 12 - '01,02' -> ()
ok 13 - no warnings
1..13
|