使用python从文本文件解析IP地址/网络

lor*_*das 0 python regex ip

我有以下文本文件,我需要一些解析IP地址的帮助.

文本文件是表单

abc 10.1.1.1/32   aabbcc
def 11.2.0.0/16   eeffgg
efg 0.0.0.0/0   ddeeff
Run Code Online (Sandbox Code Playgroud)

换句话说,一堆IP网络作为日志文件的一部分存在.输出应如下所示:

10.1.1.1/32
11.2.0.0/16
0.0.0.0/0
Run Code Online (Sandbox Code Playgroud)

我有以下代码但不输出所需信息

file = open(filename, 'r')
for eachline in file.readlines():
    ip_regex = re.findall(r'(?:\d{1,3}\.){3}\d{1,3}', eachline)
    print ip_regex
Run Code Online (Sandbox Code Playgroud)

aba*_*ert 5

首先,你的正则表达式甚至不会尝试捕获除了四个虚线数字之外的任何东西,所以当然它不会与其他任何东西相匹配,就像/32最后一样.如果你只是添加,例如,/\d{1,2}到最后,它将解决这个问题:

(?:\d{1,3}\.){3}\d{1,3}/\d{1,2}
Run Code Online (Sandbox Code Playgroud)

正则表达式可视化

Debuggex演示


但是,如果你不能很好地理解正则表达式,那么你可能不应该使用正则表达式作为你永远无法调试或扩展的"魔法".使用str类似splitor的方法有点冗长find,但对于新手来说可能更容易理解:

for line in file:
    for part in line.split()
        try:
            address, network = part.split('/')
            a, b, c, d = address.split('.')
        except ValueError:
            pass # not in the right format
        else:
            # do something with part, or address and network, or whatever
Run Code Online (Sandbox Code Playgroud)

作为旁注,根据您对这些事情的实际操作,您可能希望使用ipaddress模块(或Pydex for 2.6-3.2 上的backport)而不是字符串解析:

>>> import ipaddress
>>> s = '10.1.1.1/32'
>>> a = ipaddress.ip_network('10.1.1.1/32')
Run Code Online (Sandbox Code Playgroud)

您可以将其与上述任何一项结合使用:

for line in file:
    for part in line.split():
        try:
            a = ipaddress.ip_network(part)
        except ValueError:
            pass # not the right format
        else:
            # do something with a and its nifty methods
Run Code Online (Sandbox Code Playgroud)