randos has asked for the wisdom of the Perl Monks concerning the following question:

Hi all. Can someone please help me with the regex below to match all of the numbers after either the letters 'cms' or 'cqone' and with 0 or more non-word characters or 0s preceding? Here is what I have:

my @list = ('CMS=11111','cms11111','cms00000011111','cms11111','cms:11 +111','cms 11111','cms 11111 22222 33333','cms 11111,22222,33333'); foreach (@list) { print "$_\n"; my @matches = m/(?:cms|cqone)\W*0*(\d+)/gi; foreach (@matches) { print "\t$_\n"; }

Unfortunately this only ever matches the 11111. I need it to also match the 22222 and 33333 etc... Can someone please point me in the right direction?

Replies are listed 'Best First'.
Re: multiple regex matches
by wink (Scribe) on Sep 23, 2011 at 21:55 UTC

    Your code only finds numbers that are preceded by the strings cms or cqone. Since those strings are only before the 11111 on each line, that's all it will match. This will check for the string at the beginning of the line and then look for numbers:

    my @list = ('CMS=11111','cms11111','cms00000011111','cms11111','cms:11 +111','cms 11111','cms 11111 22222 33333','cms 11111,22222,33333'); foreach (@list) { print "$_\n"; my @matches; if(/^(?:cms|cqone)/i) { @matches = /0*(\d+)/g; } foreach (@matches) { print "\t$_\n"; } }
Re: multiple regex matches
by ikegami (Patriarch) on Sep 23, 2011 at 19:20 UTC
    my ($numbers) = 'cms 111,222' =~ /^cms[= ]?([0-9]+(?:[ ,][0-9]+)*)\z/; my @numbers = $numbers =~ /([0-9]+)/g;
Re: multiple regex matches
by AnomalousMonk (Archbishop) on Sep 23, 2011 at 23:11 UTC
    >perl -wMstrict -le "my @list = ( qw(CMS=11111 cms11111 cms00000011111 cms11111 cms:11111), 'cms 11111', 'cms 11111 22222 33333', 'cms 11111,22222,33333', qw(cms cmsxxxx), ); ;; my $start = qr{ \b (?: (?i) cms | cqone) \W* 0* }xms; my $then = qr{ \G [\s,]+ }xms; foreach (@list) { printf qq{'$_' -> }; my @matches = m{ (?: $start | $then) (\d+) }xmsg; printf qq{($_) } for @matches; print ''; } " 'CMS=11111' -> (11111) 'cms11111' -> (11111) 'cms00000011111' -> (11111) 'cms11111' -> (11111) 'cms:11111' -> (11111) 'cms 11111' -> (11111) 'cms 11111 22222 33333' -> (11111) (22222) (33333) 'cms 11111,22222,33333' -> (11111) (22222) (33333) 'cms' -> 'cmsxxxx' ->