我怎么能分割字符串并保留空格呢?

时间:2013-06-28 11:07:49

标签: ruby string split whitespace

我在Python中做了以下事情:

s = 'This is a text'
re.split('(\W)', s)
# => ['This', ' ', 'is', ' ', 'a', 'text']

效果很好。我如何在Ruby中进行相同的拆分?

我试过这个,但它吃掉了我的空白:

s = "This is a text"
s.split(/[\W]/)
# => ["This", "is", "a", "text"]

2 个答案:

答案 0 :(得分:6)

来自String#split documentation

  

如果模式包含组,则将返回相应的匹配项   阵列也是如此。

这在Ruby中与在Python中相同,方括号用于指定字符类,而不是匹配组:

"foo bar baz".split(/(\W)/)
# => ["foo", " ", "bar", " ", "baz"]

答案 1 :(得分:1)

toro2k的回答是最直截了当的。可替代地,

string.scan(/\w+|\W+/)
相关问题