如何跨新行拆分字符串并保留空行? [英] How to split string across new lines and keep blank lines?
问题描述
给定红宝石代码:
"aaaa\nbbbb\n\n".split(/\n/)
输出:
["aaaa", "bbbb"]
我希望输出包含由 \n\n
指示的空行——我希望结果是:
I would like the output to include the blank line indicated by \n\n
-- I want the result to be:
["aaaa", "bbbb", ""]
获得准确结果的最简单/最好的方法是什么?
What is the easiest/best way to get this exact result?
推荐答案
对于此任务,我建议使用 lines
而不是 split
.lines
将保留尾随换行符,这样您就可以看到所需的空行.使用chomp
清理:
I'd recommend using lines
instead of split
for this task. lines
will retain the trailing line-break, which allows you to see the desired empty-line. Use chomp
to clean up:
"aaaa\nbbbb\n\n".lines.map(&:chomp)
[
[0] "aaaa",
[1] "bbbb",
[2] ""
]
<小时>
其他更复杂的方法是:
Other, more convoluted, ways of getting there are:
"aaaa\nbbbb\n\n".split(/(\n)/).each_slice(2).map{ |ary| ary.join.chomp }
[
[0] "aaaa",
[1] "bbbb",
[2] ""
]
它利用了在 split
中使用捕获组的优势,它返回带有被分割的中间文本的分割文本.each_slice
然后将元素分组为两个元素的子数组.map
获取每个两个元素的子数组,在 join
之后是 chomp
.
It's taking advantage of using a capture-group in split
, which returns the split text with the intervening text being split upon. each_slice
then groups the elements into two-element sub-arrays. map
gets each two-element sub-array, does the join
followed by the chomp
.
或者:
"aaaa\nbbbb\n\n".split(/(\n)/).delete_if{ |e| e == "\n" }
[
[0] "aaaa",
[1] "bbbb",
[2] ""
]
以下是 split
返回的内容:
Here's what split
is returning:
"aaaa\nbbbb\n\n".split(/(\n)/)
[
[0] "aaaa",
[1] "\n",
[2] "bbbb",
[3] "\n",
[4] "",
[5] "\n"
]
我们不经常使用它,但它可能很有用.
We don't see that used very often, but it can be useful.
这篇关于如何跨新行拆分字符串并保留空行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!