gpt4 book ai didi

arrays - 如何在 ruby​​ 中使用空行作为分隔符将字符串拆分为数组?

转载 作者:数据小太阳 更新时间:2023-10-29 07:25:25 26 4
gpt4 key购买 nike

如何拆分字符串,例如:

aaaaa
bbbb

aaaaa
ccccccc

aaa
rrrrt

使用空行作为分隔符放入一个数组中?

最佳答案

嗯,用String#split

'aaaaa bbbb'.split
=> ["aaaaa", "bbbb"]

split(pattern=nil, [limit]) → an_array

Divides str into substrings based on a delimiter, returning an array of these substrings.

[...]

If pattern is nil, the value of $; is used. If $; is nil (which is the default), str is split on whitespace as if ' ' were specified.

更新:

要在空行上拆分,可以使用 /\n{2,}/ 模式。它还处理由多个空行分隔的段落:

a = <<END
aaaaa
bbbb


aaaaa
ccccccc

aaa
rrrrt
END

a.split(/\n{2,}/)
=> ["aaaaa\nbbbb", "aaaaa\nccccccc", "aaa\nrrrrt\n"]

关于arrays - 如何在 ruby​​ 中使用空行作为分隔符将字符串拆分为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54402556/

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