需要帮助将 IP 子网与 ruby 正则表达式匹配



我正在尝试匹配IP的前两个八位字节以确定网络子网。 IP 以10.4310.4410.46开头但不10.45,试图与此表达式匹配10.4{3|4|6}但它只匹配10.4410.46

任何猜测为什么不匹配10.43

虽然正则表达式可以工作(@Stefan已经提供了一个(,但我不知道您的实现,但IPAddr标准库可能会让您感兴趣,例如

acceptable_sub_nets = ["10.43.0.0","10.44.0.0","10.46.0.0"]
my_list_of_ips.select do |ip|
acceptable_sub_nets.include?(IPAddr.new(ip).mask(16).to_s)
end

例如

IPAddr.new("10.43.22.19").mask(16).to_s
#=> "10.43.0.0"
IPAddr.new("192.168.0.1").mask(16).to_s
#=> "192.168.0.0"

此外,您可以执行类似操作

acceptable_sub_nets = ["10.43.0.0","10.44.0.0","10.46.0.0"].map do |subnet|
IPAddr.new(subnet).mask(16).to_range
end
my_list_of_ips.select do |ip|
acceptable_sub_nets.any? {|range| range.cover?(ip) } 
end

subnet_range = IPAddr.new("10.43.0.0").mask(16).to_range
subnet_range.cover?("10.43.22.19")
#=> true
subnet_range.cover?("192.168.0.1")
#=> false

更新(谢谢@JordanRunning(

第二个选项可以简化为

acceptable_sub_nets = [
#including the mask range
IPAddr.new("10.43.0.0/16"),
IPAddr.new("10.44.0.0/16"),
IPAddr.new("10.46.0.0/16")]
my_list_of_ips.select do |ip|
acceptable_sub_nets.any? {|range| range.include?(ip) } 
end

这不需要转换为Range,而是直接利用IPAddr#include?

最新更新