A more elegant way to parse a string with ruby regular expression using variable grouping?

Posted by i0n on Stack Overflow See other posts from Stack Overflow or by i0n
Published on 2011-11-30T16:57:53Z Indexed on 2011/11/30 17:50 UTC
Read the original article Hit count: 229

Filed under:
|

At the moment I have a regular expression that looks like this:

^(cat|dog|bird){1}(cat|dog|bird)?(cat|dog|bird)?$

It matches at least 1, and at most 3 instances of a long list of words and makes the matching words for each group available via the corresponding variable.

Is there a way to revise this so that I can return the result for each word in the string without specifying the number of groups beforehand?

^(cat|dog|bird)+$

works but only returns the last match separately , because there is only one group.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about regex