ruby .split('\n') 不会在新行上拆分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16406381/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:55:35  来源:igfitidea点击:

ruby .split('\n') not splitting on new line

rubystring

提问by user2012677

Why does this string not split on each "\n"? (RUBY)

为什么这个字符串不会在每个“\n”上拆分?(红宝石)

"ADVERTISING [7310]\n\t\tIRS NUMBER:\t\t\t\t061340408\n\t\tSTATE OF INCORPORATION:\t\t\tDE\n\t\tFISCAL YEAR END:\t\t\t0331\n\n\tFILING VALUES:\n\t\tFORM TYPE:\t\t10-Q\n\t\tSEC ACT:\t\t1934 Act\n\t".split('\n')
>> ["ADVERTISING [7310]\n\t\tIRS NUMBER:\t\t\t\t061340408\n\t\tSTATE OF INCORPORATION:\t\t\tDE\n\t\tFISCAL YEAR END:\t\t\t0331\n\n\tFILING VALUES:\n\t\tFORM TYPE:\t\t10-Q\n\t\tSEC ACT:\t\t1934 Act\n\t"]

回答by Mori

You need .split("\n"). String interpolation is needed to properly interpret the new line, and double quotes are one way to do that.

你需要.split("\n"). 需要字符串插值来正确解释新行,双引号是一种方法。

回答by jbr

In Ruby single quotes around a string means that escape characters are not interpreted. Unlike in C, where single quotes denote a single character. In this case '\n'is actually equivalent to "\\n".

在 Ruby 中,字符串周围的单引号意味着不解释转义字符。不像在 C 中,单引号表示单个字符。在这种情况下'\n'实际上相当于"\\n".

So if you want to split on \nyou need to change your code to use double quotes.

因此,如果您想拆分,则\n需要更改代码以使用双引号。

.split("\n")

.split("\n")

回答by 23inhouse

Ruby has the methods String#each_lineand String#lines

Ruby 有方法String#each_lineString#lines

returns an enum: http://www.ruby-doc.org/core-1.9.3/String.html#method-i-each_line

返回一个枚举:http: //www.ruby-doc.org/core-1.9.3/String.html#method-i-each_line

returns an array: http://www.ruby-doc.org/core-2.1.2/String.html#method-i-lines

返回一个数组:http: //www.ruby-doc.org/core-2.1.2/String.html#method-i-lines

I didn't test it against your scenario but I bet it will work better than manually choosing the newline chars.

我没有针对您的场景对其进行测试,但我敢打赌它比手动选择换行符效果更好。

回答by Mark Swardstrom

Or a regular expression

或者正则表达式

.split(/\n/)

回答by fotanus

You can't use single quotes for this:

您不能为此使用单引号:

"ADVERTISING [7310]\n\t\tIRS NUMBER:\t\t\t\t061340408\n\t\tSTATE OF INCORPORATION:\t\t\tDE\n\t\tFISCAL YEAR END:\t\t\t0331\n\n\tFILING VALUES:\n\t\tFORM TYPE:\t\t10-Q\n\t\tSEC ACT:\t\t1934 Act\n\t".split("\n")