我有一个包含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。
答案 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