tags:

views:

159

answers:

3

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"]
+3  A: 

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.

Adam Bellaire
+5  A: 

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

Brian Young
A: 

Or if you want to be REALLY explicit about the separators:

"foo bar, zap-foo, baz".split(/ |, |,/)

=> ["foo", "bar", "zap-foo", "baz"]
btelles