Python正则表达式匹配和提取IP地址
No.1 IPv4
下面是IPv4的IP正则匹配实例:
简单的匹配给定的字符串是否是ip地址
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地址
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
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
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
总结
相关推荐
RuoShangM 2020-02-27
Buerzhu 2019-12-02
dailinqing 2019-10-28
shijinling0 2019-06-29
LHpython 2019-04-23
Python探路者 2019-04-18
JamesHammer 2019-04-17
PythonBiglove 2018-12-25
JamesHammer 2019-04-05
pythonpycharm 2013-12-25
yoyoshadow 2013-11-20
impressyourcat 2018-03-22