Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regexp split string by commas and spaces, but ignore hyphenated words?

Tags:

regex

ruby

I need a regexp to split a string by commas and/or spaces, but ignore hyphenated words -- what's the best way to do this?

so, for example -- I'd like this ...

"foo bar, zap-foo, baz".split(/[\s]+/)

to return

["foo", "bar", "zap-foo", "baz"]

but when I do that it includes the commas like this ...

["foo", "bar,", "zap-foo,", "baz"]
like image 483
rsturim Avatar asked Dec 02 '09 18:12

rsturim


2 Answers

"foo bar, zap-foo, baz".split(/[\s,]+/)

like image 87
Brian Young Avatar answered Nov 11 '22 17:11

Brian Young


You can specify a character class which says to split on things that are not hyphens or word characters:

"foo bar, zap-foo, baz".split(/[^\w-]+/)

Or you can split only on whitespace and commas using a character class such as the one Ocson has provided.

like image 27
Adam Bellaire Avatar answered Nov 11 '22 19:11

Adam Bellaire