Python正则表达式匹配和提取IP地址

时间:2022-11-17 16:35:22

linux

no.1 ipv4

下面是ipv4的ip正则匹配实例:

简单的匹配给定的字符串是否是ip地址

?
1
2
3
4
5
import re
if re.match(r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$", "236.168.192.1"):
  print "ip vaild"
 else:
  print "ip invaild"

精确的匹配给定的字符串是否是ip地址

?
1
2
3
4
5
import re
if re.match(r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$", "236.168.192.1"):
  print "ip vaild"
 else:
  print "ip invaild"

简单从长文本中提取ip

?
1
2
3
4
5
6
7
import re
string_ip = "is this 236.168.192.1 ip 12321"
result = re.findall(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", string_ip)
if result:
  print result
else:
  print "re cannot find ip"

精准提取ip

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import re
string_ip = "is this 236.168.192.1 ip 12321"
result = re.findall(r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b", string_ip)
if result:
  print result
else:
  print "re cannot find ipno.2 ipv6
string_ipv6="1050:0:0:0:5:600:300c:326b"
#匹配是否满足ipv6格式要求,请注意例子里大小写不敏感
if re.match(r"^(?:[a-f0-9]{1,4}:){7}[a-f0-9]{1,4}$", string_ipv6, re.i):
  print "ipv6 vaild"
else:
  print "ipv6 invaild"
#提取ipv6,例子里大小写不敏感
result = re.findall(r"(?<![:.\w])(?:[a-f0-9]{1,4}:){7}[a-f0-9]{1,4}(?![:.\w])", string_ipv6, re.i)
#打印提取结果
print result

总结

以上所述是小编给大家介绍的python正则表达式匹配和提取ip地址,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:https://fashengba.com/post/Python-regular-matches-ip.html