只搜索完全匹配的

2024-04-20 05:01:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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。我想一定有办法强迫它回到我的输入。。。你知道吗


Tags: nameipinfo示例列表stringaddressmac
1条回答
网友
1楼 · 发布于 2024-04-20 05:01:53

不要使用正则表达式。只需寻找字符串本身。你知道吗

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 for a, b in zip(ip_address, key))作为条件。你知道吗

相关问题 更多 >