regexp通过逗号和空格分隔字符串,但是忽略连字符?

时间:2021-10-28 21:36:17

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?

我需要一个regexp来通过逗号和/或空格分隔字符串,但是忽略带连字符的单词——最好的方法是什么?

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"]

4 个解决方案

#1


31  

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

“foo酒吧,zap-foo,巴兹”.split(/[\ s]+ /)

#2


5  

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.

或者,您只能在空格和逗号上使用一个字符类,比如Ocson提供的一个字符类。

#3


2  

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

或者如果你想对隔板很清楚的话:

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

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

#4


2  

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

#1


31  

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

“foo酒吧,zap-foo,巴兹”.split(/[\ s]+ /)

#2


5  

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.

或者,您只能在空格和逗号上使用一个字符类,比如Ocson提供的一个字符类。

#3


2  

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

或者如果你想对隔板很清楚的话:

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

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

#4


2  

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