简体   繁体   English

从Ruby字符串中提取信息

[英]Extracting Information from a Ruby String

I have a text file similar to this on a remote device: 我在远程设备上有一个与此类似的文本文件:

 D0-23-DB-31-04-3E%20192.168.4.42%20dnat
 68-A8-6D-0C-38-B2%20192.168.4.40%20dnat

I created a small Ruby script to convert this to a string and post it to my Rails application: 我创建了一个小的Ruby脚本来将其转换为字符串并将其发布到我的Rails应用程序:

 def chilli_list
  hash = File.open("/tmp/client_list", "rb").read
  return hash
 end

The output then looks like: 然后输出如下:

"D0-23-DB-31-04-3E%20192.168.4.42%20dnat\n68-A8-6D-0C-38-B2%20192.168.4.40%20dnat\n" 

I need to extract the information bit by bit and display in a view. 我需要逐位提取信息并在视图中显示。 So far, I've not got far. 到目前为止,我还没有走得太远。 I tried the following which is OK: 我尝试了以下可以:

str = "D0-23-DB-31-04-3E%20192.168.4.42%20dnat\n68-A8-6D-0C-38-B2%20192.168.4.40%20dpass\n" 

str.each_line do |line|
  puts line.split(" ").first
  puts line.split(" ").second
end

Is that the best way to do it or is there a better way? 这是最好的方式还是有更好的方法?

Finally and most importantly, I also need to perform a few calculations on the string. 最后也是最重要的是,我还需要对字符串执行一些计算。 I can count the lines with str.lines.count , but what I need is a count of the lines where the third value == nat as in the example above. 我可以使用str.lines.count计算行str.lines.count ,但我需要的是第三个值== nat的行的计数,如上例所示。

How can I go about that? 我该怎么办呢?

First, here's how to convert from HTML encoding back into a normal string: 首先,这里是如何将HTML编码转换回普通字符串:

require 'uri'
URI.decode('D0-23-DB-31-04-3E%20192.168.4.42%20dnat') # => "D0-23-DB-31-04-3E 192.168.4.42 dnat"

Here's how to break the entire string into separate decode lines: 以下是如何将整个字符串分解为单独的解码行:

"D0-23-DB-31-04-3E%20192.168.4.42%20dnat\n68-A8-6D-0C-38-B2%20192.168.4.40%20dnat\n".split("\n")
  .map{ |l| URI.decode(l) }

which results in this array in IRB: 这导致IRB中的这个数组:

[
    [0] "D0-23-DB-31-04-3E 192.168.4.42 dnat",
    [1] "68-A8-6D-0C-38-B2 192.168.4.40 dnat"
]

Add on .count{ |l| l[/ dnat$/] } 添加.count{ |l| l[/ dnat$/] } .count{ |l| l[/ dnat$/] } to the end of the previous command and you'll have your count: .count{ |l| l[/ dnat$/] }到上一个命令的末尾,你将有你的计数:

"D0-23-DB-31-04-3E%20192.168.4.42%20dnat\n68-A8-6D-0C-38-B2%20192.168.4.40%20dnat\n".split("\n")
  .map{ |l| URI.decode(l) }
  .count{ |l| l[/ dnat$/] }

Which returns 2 . 返回2

You could also probably simplify the whole process by just directly counting the number of 'nat' occurrences: 您也可以通过直接计算'nat'出现次数来简化整个过程:

"D0-23-DB-31-04-3E%20192.168.4.42%20dnat\n68-A8-6D-0C-38-B2%20192.168.4.40%20dnat\n".scan('nat').count

Which also returns 2 . 哪个也返回2

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

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