开发者

How to split Ruby string by "\r\n"?

Given a string like:

s = "G o o d\r\nDay\r\n\r\n\r\nStack\r\n\r\nOverflow\r\n"

I would like to:

  • Split it by (\r\n)+, i.e. I would like to get: ["G o o d", "Day", "Stac开发者_C百科k", "Overflow"]

    I tried s.split(/(\r\n)+/) but it doesn't give me the expected result.

    Why ? How could I get the expected result ?

  • Get the number of \r\n in array, i.e. the expected result is: [1, 3, 2]

    How would you do this ?

I use Ruby 1.9.2.


Almost, try this:

s.split /[\r\n]+/
s.scan(/[\r\n]+/).map { |e| e.size/2 }

This gives [1,3,2,1] which is possibly the "real" answer. But otherwise, s.chomp.scan... would give [1,3,2].


Here's how I'd go about it:

s = "G o o d\r\nDay\r\n\r\n\r\nStack\r\n\r\nOverflow\r\n"

s.split(/[\r\n]+/) # => ["G o o d", "Day", "Stack", "Overflow"]


You want to split by /[\r\n]+/

"G o o d\r\nDay\r\n\r\n\r\nStack\r\n\r\nOverflow\r\n".split(/[\r\n]+/)


Your split(/(\r\n)+/) doesn't work as you expect because capture groups are included in the returned array:

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

An easy solution would be to split on \r\n and the throw away the empties:

s.split(/\r\n/).reject { |s| s == '' }


You shouldn't be getting \r\n in your strings, unless you're reading in a Windows text file in binary mode. Read it in in text mode, and Ruby will fix the \rs for you automatically.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜