如何用空格或点分割字符串?

时间:2022-11-28 21:38:59

For example as input I may receive "qwer.qwer" or "qwer qwer". In both cases I need to split this string so I get result:

例如,作为输入,我可能会收到“qwer”。qwer”或“qwer qwer”。在这两种情况下,我都需要拆分这个字符串,这样我就得到了结果:

["qwer", "qwer"]

Can I use regex as a spliter, and what this regex must look like?

我可以使用regex作为一个spliter吗?这个regex应该是什么样子?

3 个解决方案

#1


6  

'qwer.qwer'.split(/\s|\./)
# => ["qwer", "qwer"]
'qwer qwer'.split(/\s|\./)
# => ["qwer", "qwer"]

#2


4  

Use character class [.\s]:

使用字符类[\ s]。:

"qwer.qwer".split(/[.\s]/) # => ["qwer", "qwer"]
"qwer qwer".split(/[.\s]/) # => ["qwer", "qwer"]

#3


3  

Do as below using String#scan instead of Strin#split:

使用字符串#scan代替Strin#split:

"qwer.qwer".scan(/\w+/)
# => ["qwer", "qwer"]
"qwer qwer".scan(/\w+/)
# => ["qwer", "qwer"]

#1


6  

'qwer.qwer'.split(/\s|\./)
# => ["qwer", "qwer"]
'qwer qwer'.split(/\s|\./)
# => ["qwer", "qwer"]

#2


4  

Use character class [.\s]:

使用字符类[\ s]。:

"qwer.qwer".split(/[.\s]/) # => ["qwer", "qwer"]
"qwer qwer".split(/[.\s]/) # => ["qwer", "qwer"]

#3


3  

Do as below using String#scan instead of Strin#split:

使用字符串#scan代替Strin#split:

"qwer.qwer".scan(/\w+/)
# => ["qwer", "qwer"]
"qwer qwer".scan(/\w+/)
# => ["qwer", "qwer"]