由两个或多个连续的空格分割字符串,但不是单个

时间:2015-03-18 06:09:17

标签: ruby string split

我有

str = "this     is    simpl e    string 98"

我需要这样的东西

["this","is","simple","string","98"]

我这样做了:

str.split(" ")
# => ["this","is","simpl","e","string","98"]

1 个答案:

答案 0 :(得分:2)

使用gsub函数删除两个字母之间存在的单个空格,然后按顺序拆分以获得所需的输出。

> str = "this     is    simpl e    string 98"
> str.gsub(/(?<=[[:alpha:]])\s(?=[[:alpha:]])/,"").split()
=> ["this", "is", "simple", "string", "98"]