简体   繁体   English

如何从 ruby​​ 中的多行字符串获取从第 n 行到最后一行的数据?

[英]How to get the data from line number n to last line from a multi-line string in ruby?

I am executing the following curl request in ruby:我正在 ruby​​ 中执行以下 curl 请求:

cmd="curl --silent --insecure -i -X GET -u \"local\username:password\" \"https://example.com/Console/Changes\""
response = `cmd`

It is resulting in the following output:它导致以下输出:

在此处输入图片说明

From the above output it seems to be the response variable contains a multi-line string value.从上面的输出看来,响应变量包含一个多行字符串值。 Just to confirm, I am trying to print the type of 'response' variable here:只是为了确认,我试图在此处打印“响应”变量的类型:

puts response.class

Output here is:这里的输出是:

String细绳

How to extract header info and the json body separately from the above response?如何从上述响应中分别提取标头信息和 json 正文?

There's better ways to do HTTP requests in Ruby, eg using the standard library's Net::HTTP .在 Ruby 中有更好的方法来处理 HTTP 请求,例如使用标准库的Net::HTTP

Having said that, I'll answer your question.说了这么多,我来回答你的问题。

The HTTP standard specifies that the header and the body are separated by an empty line containing just a CRLF ( \\r\\n ). HTTP 标准指定标头和正文由仅包含 CRLF ( \\r\\n ) 的空行分隔。 Each line of the header also ends with a CRLF.标题的每一行也以 CRLF 结尾。 Thus, we can simply split the response at the first occurrence of two CRLF, ie at the string "\\r\\n\\r\\n" .因此,我们可以简单地在第一次出现两个 CRLF 时拆分响应,即在字符串"\\r\\n\\r\\n"

Since this sequence might also appear in the body, we need to specify that we want our split to have at most 2 elements.由于这个序列也可能出现在正文中,我们需要指定我们希望我们的拆分最多有 2 个元素。

header, body = response.split("\r\n\r\n", 2)

Note though that with this the last header line will not end in "\\r\\n" , but that shouldn't be a problem.请注意,尽管如此,最后的标题行不会以"\\r\\n"结尾,但这应该不是问题。 The technically more correct version would be to split at "\\r\\n" followed by a "\\r\\n" .技术上更正确的版本是在"\\r\\n"后跟一个"\\r\\n"处拆分。 That way we don't strip the trailing "\\r\\n" when splitting.这样我们就不会在拆分时去掉尾随的"\\r\\n" This can be done with a regular expression using a look-behind:这可以通过使用后视的正则表达式来完成:

header, body = response.split(/(?<=\r\n)\r\n/, 2)

The answer to your question in the title is a bit different though:不过,您在标题中的问题的答案有点不同:

How to get the data from line number n to last line from a multi-line string in ruby?如何从 ruby​​ 中的多行字符串获取从第 n 行到最后一行的数据?

response.lines[n..].join

(Before Ruby 2.6 the range needs to be specified as n..-1 .) (在 Ruby 2.6 之前,范围需要指定为n..-1 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM