我有下面的文本文件,我需要一些帮助解析出IP地址。
文本文件的格式是
abc 10.1.1.1/32 aabbcc
def 11.2.0.0/16 eeffgg
efg 0.0.0.0/0 ddeeff
换句话说,一堆IP网络作为日志文件的一部分存在。输出应如下:
10.1.1.1/32
11.2.0.0/16
0.0.0.0/0
我有下面的代码,但没有输出所需的信息
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
首先,您的regex甚至不试图捕获任何东西,除了四个点数字,所以它当然不会匹配任何其他东西,比如最后的
/32
。如果你只是在结尾加上/\d{1,2}
,它会解决这个问题:Debuggex Demo
但是,如果您对正则表达式的理解不足以理解这一点,那么您可能不应该将正则表达式用作永远无法调试或扩展的“魔法”。使用
str
方法(如split
或find
)会更详细一些,但对于新手来说可能更容易理解:另一方面,根据实际使用这些内容的情况,您可能希望使用^{} 模块(或the backport on PyPI用于2.6-3.2),而不是字符串解析:
您可以将其与以上任一项结合起来:
在这种特殊情况下,regex可能会被过度终止,您可以使用
split
这将产生一个字符串列表,即ip地址。
相关问题 更多 >
编程相关推荐