开发者

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

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 exampl开发者_开发技巧e -- 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.


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

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

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜