gpt4 book ai didi

ruby - 我怎样才能拆分字符串并保留空格呢?

转载 作者:太空宇宙 更新时间:2023-11-03 17:16:42 26 4
gpt4 key购买 nike

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

最佳答案

来自 String#split documentation :

If pattern contains groups, the respective matches will be returned in the array as well.

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

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

关于ruby - 我怎样才能拆分字符串并保留空格呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17363297/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com