You repeat your capture group , with each repeated match, the previous content is overwritten. Thus, only the last match of your second capture group is available at the end.
You can change the second capture group to
^\s*([a-z_]\w*)((?:\s*,\s*(?:[a-z_]\w*))*)\s*$
Then the result will be, "banana, orange, peanuts" in your second group. I'm not sure if you want this.
If you want to check that the string has this pattern and extracts every word. I would do it in two steps.
Check the pattern with your regular expression.
If the pattern is correct, remove the leading and trailing spaces and divide by \s*,\s* .
source share