ruby 如何跨新行拆分字符串并保留空行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12062126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to split string across new lines and keep blank lines?
提问by Kirk Woll
Given the ruby code:
鉴于红宝石代码:
"aaaa\nbbbb\n\n".split(/\n/)
This outputs:
这输出:
["aaaa", "bbbb"]
I would like the output to include the blank line indicated by \n\n-- I want the result to be:
我希望输出包含由\n\n-指示的空行,我希望结果是:
["aaaa", "bbbb", ""]
What is the easiest/best way to get this exact result?
获得这个确切结果的最简单/最好的方法是什么?
回答by the Tin Man
I'd recommend using linesinstead of splitfor this task. lineswill retain the trailing line-break, which allows you to see the desired empty-line. Use chompto clean up:
我建议使用lines而不是split用于此任务。lines将保留尾随换行符,这样您就可以看到所需的空行。使用chomp清理:
"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] ""
]
It's taking advantage of using a capture-group in split, which returns the split text with the intervening text being split upon. each_slicethen groups the elements into two-element sub-arrays. mapgets each two-element sub-array, does the joinfollowed by the chomp.
它利用了在 中使用捕获组的优势split,它返回拆分文本,中间文本被拆分。each_slice然后将元素分组为两个元素的子数组。map获取每个二元素子数组,join然后执行chomp.
Or:
或者:
"aaaa\nbbbb\n\n".split(/(\n)/).delete_if{ |e| e == "\n" }
[
[0] "aaaa",
[1] "bbbb",
[2] ""
]
Here's what splitis returning:
这split是返回的内容:
"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.
我们没有看到经常使用它,但它可能很有用。
回答by Mark Byers
You can supply a negative argument for the second parameter of split to avoid stripping trailing empty strings;
您可以为 split 的第二个参数提供一个负参数,以避免剥离尾随的空字符串;
"aaaa\nbbbb\n\n".split(/\n/, -1)
Note that this will give you one extra empty string compared to what you want.
请注意,与您想要的相比,这将为您提供一个额外的空字符串。
回答by Dave Newton
You can use the numeric argument, but IMO it's a bit tricky since (IMO) it's not quite consistent with what I'd expect, and AFAICT you'd want to trim the last null field:
您可以使用数字参数,但 IMO 有点棘手,因为(IMO)它与我期望的不太一致,并且 AFAICT 您想要修剪最后一个空字段:
jruby-1.6.7 :020 > "aaaa\nbbbb\n\n".split(/\n/, -1)[0..-2]
=> ["aaaa", "bbbb", ""]

