I'm trying to match (along with capture groups) the following input:
favorite colors are red orange yellow
favorite colors are red orange
The first phrase has 3 colors, the second phrase has 2 colors.
My regex is:
/favorite colors are (.*) (.*) (.*)/i
However, this regex only works if I have 3 colors. How could I rewrite this regex so that it can also accept 2 colors? I've tried adding a ? to the end of the 3 capture group but that requires that my input phrase to have a trailing space.
I don't mind having the 3 color be empty in the capture group if the 3rd color isn't supplied.
As per the http://stackoverflow.com/questions/12451731 post, the suggested fix as /favorite colors are (.*) (.*)(?: (.*))?/i
, however, it does not work because it matches red orange as group 1, and yellow as group 2, while red should be in group 1, orange should be in group 2 and yellow should be in group 3. The http://stackoverflow.com/questions/8991178 post suggests using [^\s]
, but it turns out that matches trailing dots.