如何解析IP地址的字符串

时间:2016-01-07 21:58:19

标签: ruby-on-rails ruby ruby-on-rails-4

我有一个包含MAC地址的数据库表。目前我这样做:

 <% @devices.each do |device| %>
      <tr>
        <td><%= device.mac_address %></td>
      </tr>
  <% end %>

我有两个名为data的变量,其中包含一个字符串:

Host is up (0.00s latency). MAC Address: 00:95:7F:A9:A3:81 (Unknown) Nmap scan report for 192.168.1.3 Host is up (0.0020s latency). MAC Address: 00:66:19:38:2E:7E (Unknown) Nmap scan report for 192.168.1.4 
Host is up (0.0030s latency). MAC Address: 00:66:19:38:2F:00 (Unknown) 
Nmap scan report for 192.168.1.5 

当我循环MAC地址时,如何解析data以查找Mac地址后面的IP?如果循环中的当前MAC地址为00:95:7F:A9:A3:81,则需要输出192.168.1.3作为IP。

2 个答案:

答案 0 :(得分:1)

默想:

MAC_ADDRESSES = %w[
  00:95:7F:A9:A3:81
  00:66:19:38:2E:7E
  00:66:19:38:2F:00
]

IP_REGEX = /(?:\d{1,3}\.){3}\d{1,3}/

RESULT = 'Host is up (0.00s latency). MAC Address: 00:95:7F:A9:A3:81 (Unknown) Nmap scan report for 192.168.1.3 Host is up (0.0020s latency). MAC Address: 00:66:19:38:2E:7E (Unknown) Nmap scan report for 192.168.1.4 Host is up (0.0030s latency). MAC Address: 00:66:19:38:2F:00 (Unknown) Nmap scan report for 192.168.1.5'

pairs = MAC_ADDRESSES.map { |mac|
  [mac, RESULT[/#{mac}.+?(#{IP_REGEX})/, 1]]
}.to_h

pairs 
# => {"00:95:7F:A9:A3:81"=>"192.168.1.3",
#     "00:66:19:38:2E:7E"=>"192.168.1.4",
#     "00:66:19:38:2F:00"=>"192.168.1.5"}

pairs['00:66:19:38:2E:7E'] # => "192.168.1.4"

答案 1 :(得分:0)

我在这里使用Regex:

macs.each do |mac|
  if @result =~ /#{mac.mac_address}.*?for (\d+\.\d+\.\d+\.\d+)/
    ip = $1
    puts "#{mac} - #{ip}"
  end
end