Monday, April 30, 2012

Match comma separated list with Ruby Regex

Given the following string, I'd like to match the elements of the list:




foo,bar,baz




The minimum number of elements is 1, and there can be arbitrarily many. Assume no whitespace and lower case.



I've tried this, which should work, but doesn't populate all the match groups for some reason:



^([a-z]+)(?:,([a-z]+))*



That matches foo in \1 and baz (or whatever the last element is) in \2. I don't understand why I don't get a match group for bar.



Any ideas?



EDIT: Ruby 1.9.3, if that matters.



EDIT2: Rubular link: http://rubular.com/r/cDQh9SZyA2





No comments:

Post a Comment