是用re模块。具体代码如下:
import re
pattern = re.compile(
r"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))")
x = "sljflafja10.10.10.11flksjfklsajf00.00.1xxxx22.222.222.22"
y = "fjlsfjla10.10.10.10jkfsjf"
z = "10.10.10.10"
a = pattern.findall(x)
b = pattern.findall(y)
c = pattern.findall(z)
ips1 = [g[0] for g in a]
ips2 = [g[0] for g in b]
ips3 = [g[0] for g in c]
print ips1
print ips2
print ips3
输出结果:
['10.10.10.11', '22.222.222.22']
['10.10.10.10']
['10.10.10.10']
主要是IP地址的正则表达式比较复杂,python中的正则表达式使用还是比较简单的。