in reply to Matching a pattern two or four times

OK. Split seems to be the right answer - I'm not sure where my obsession with using a regex came from this morning. I think I was hoping to use it to do some level of validation of the input (just print out a warning and skip any lines which didn't match) but splitting then validating the results is more readable, if significantly longer.

In this case regexes probably weren't the best way to do it, but I still don't understand how to retrieve matched groups from a repeated group. For example:

my @lines = ("a 1 2", "b 3 4 5 6", "c 7 8 9"); foreach (@lines) { my @list = m/^[a-z](\s+\d+)+/g; print @list, "\n"; }
Does not print
1 2
3 4 5 6
7 8 9
as I might have expected, but
2
6
9
What am I missing?

Replies are listed 'Best First'.
Re: Re: Matching a pattern two or four times
by RMGir (Prior) on Sep 24, 2002 at 17:43 UTC
    What am I missing?

    2 things. First, you can't have multiple matches (//g) AND have your regex anchored at the start of the string.

    Second, the //g will return all the captured matches, so you don't need that last +. In fact, you can't HAVE that last +, or it doesn't work.

    my @lines = ("a 1 2", "b 3 4 5 6", "c 7 8 9"); foreach (@lines) { # you can't match multiple times starting at ^! my @list = m/(\s+\d+)/g; # no last + print @list, "\n"; }
    Of course, demerphq made a very good point about that regex not being sufficient to match all numbers...
    --
    Mike