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"]
"foo bar, zap-foo, baz".split(/[\s,]+/)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With