有没有办法用空格和逗号分割字符串,但在结果数组中保留逗号?

时间:2019-09-07 14:14:54

标签: ruby

我有一个像这样的字符串:

"my bike, is very big"

我想按以下方式进行拆分。

["my","bike",",","is","very","big"]

2 个答案:

答案 0 :(得分:0)

与此this answer to a similar question一起使用的#scan和正则表达式解决方案是完美的。我也想包括非正则表达式解决方案:

str = "my bike, is very big"

str = str.split(",").flat_map { |x| [x, ","] }[0...-1].map(&:split).flatten

p str

#-> ["my", "bike", ",", "is", "very", "big"]

答案 1 :(得分:0)

这是我的看法。

text = "my bike, is very big"
text_array = text.split(/(\W+)/)
parsed_text_array = text_array.map { |item| 
    next if item.eql?(" ")
    item.strip
}.compact

print parsed_text_array

# ~> ["my", "bike", ",", "is", "very", "big"]

希望这会有所帮助:)