Sunday 19 May 2019

Match comma separated list with Ruby Regex




Given the following string, I'd like to match the elements of the list and parts of the rest after the colon:




foo,bar,baz:something




I.e. I am expecting the first three match groups to be "foo", "bar", "baz". No commas and no colon. 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]+))*:(something)



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/pDhByoarbA




EDIT3: Add colon to the end, because I am not just trying to match the list. Sorry, oversimplified the problem.


Answer



This expression works for me: /(\w+)/i


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...