Python 只搜索精确的匹配项

Python 只搜索精确的匹配项,python,networking,Python,Networking,因此,我有一个非常长的列表(示例截断),其中的值如下所示: derp = [[('interface_name', 'interface-1'), ('ip_address', '10.1.1.1'), ('mac_address', 'xx:xx:xx:xx:xx:xx')], [('interface_name', 'interface 2'), ('ip_address', '10.1.1.2'), ('mac_address', 'xx:xx:xx:xx:xx:xx')], [('int

因此,我有一个非常长的列表(示例截断),其中的值如下所示:

derp = [[('interface_name', 'interface-1'), ('ip_address', '10.1.1.1'), ('mac_address', 'xx:xx:xx:xx:xx:xx')], [('interface_name', 'interface 2'), ('ip_address', '10.1.1.2'), ('mac_address', 'xx:xx:xx:xx:xx:xx')], [('interface_name', 'interface 3'), ('ip_address', '10.1.1.11'), ('mac_address', 'xx:xx:xx:xx:xx:xx')]]
我有一个函数,它遍历了那个庞大的列表,并根据IP提取了一个匹配,但问题是,它似乎匹配最后一个八位组中的任何内容,而不仅仅是精确匹配

findIP = sys.argv[1]

def arpInt(arp_info):
   for val in arp_info:
       if re.search(findIP, str(val)):
           interface = val.pop(0)
           string = val
           print string, interface[1]

arpInt(derp)

因此,在上述情况下,如果findIP='10.1.1.1',它将返回10.1.1.1和10.1.1.11。我想一定有办法强迫它回到我输入的内容…

不要使用正则表达式。只需查找字符串本身

data = [[('interface_name', 'interface-1'),
         ('ip_address', '10.1.1.1'),
         ('mac_address', 'xx:xx:xx:xx:xx:xx')],
        [('interface_name', 'interface-1a'),
         ('ip_address', '010.001.001.001'),
         ('mac_address', 'xx:xx:xx:xx:xx:xx')],
        [('interface_name', 'interface 2'),
         ('ip_address', '10.1.1.2'),
         ('mac_address', 'xx:xx:xx:xx:xx:xx')],
        [('interface_name', 'interface 3'),
         ('ip_address', '10.1.1.11'),
         ('mac_address', 'xx:xx:xx:xx:xx:xx')]]


key = '10.1.1.1'
for interface, ip, mac in data:
    if key in ip:
        #print(interface, ip)
        print([interface, ip, mac], interface[1])
当然,只有当数据中的ip地址符合您的示例时,它才起作用。。。没有前导零


如果您的地址可能有前导零,您可以比较地址的整数等价物

key = '10.1.1.1'
key = map(int, key.split('.'))
for interface, ip, mac in data:
    ip_address = ip[1]
    ip_address = map(int, ip_address.split('.'))
    if ip_address == key:
        #print(interface, ip)
        print([interface, ip, mac], interface[1])

我在这台计算机上没有Python3.x,所以我真的不知道是否可以像那样比较贴图对象。如果不是,则使用
all(a==b表示a,b在zip(ip\u地址,key))中使用
表示条件。

IPv4地址实际上是一个32位整数;带点的十进制文本表示法仅用于人类可读性。如果您将文本表示形式转换为整数,您可以正确排序和比较。对于我的初学者@RonMaupin,我深表歉意,但您能更详细地说明一下您的意思吗?添加结果:第一个八位字节乘以
16777216
2^24
),第二个八位字节乘以
65536
2^16
),第三个八位字节乘以
256
2^8
)和第四个八位字节。这将导致IPv4地址的二进制表示为32位整数。要正确排序,请使用无符号整数。您可以轻松比较整数值以获得精确匹配。IP地址放在IP报头中,由网络设备作为整数使用。IPv4地址的文本表示形式用于人的可读性,但它不是IPv4地址的真实表示和使用方式。请尝试使用联机方式来微调您正在使用的模式。特别是模式中的点,
将匹配任何字符。此外,您可以在循环的不同点打印变量,以查看代码在做什么-有时会有所帮助。这非常有效!我能够得到相同的信息,它清理了我脚本的第二部分(我没有放在这里),它实际上从接口中剥离了一些信息,并使用它来验证一些交换机/路由器配置。快速提问-在“for interface,ip,mac in data:”中,这只是给每个元组分配了一个名称吗?@DangerZone-是的,如果左侧的名称数不同于iterable的长度,它将抛出一个异常。请看这里。和。