如何检查一个字符串在python的IP地址模式匹配

2024-11-15 12:13:52
推荐回答(1个)
回答(1):

是用re模块。具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

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中的正则表达式使用还是比较简单的。