下面是IPv4的IP正则匹配表达式
1 import re 2 #简单的匹配给定的字符串是否是ip地址,下面的例子它不是IPv4的地址,但是它满足正则表达式 3 if re.match(r"^(?:[0-9]{1,3}.){3}[0-9]{1,3}$", "272.168,1,1"): 4 print "IP vaild" 5 else: 6 print "IP invaild" 7 #精确的匹配给定的字符串是否是IP地址 8 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]?)$", "223.168.1.1"): 9 print "IP vaild" 10 else: 11 print "IP invaild" 12 #简单的从长文本中提取中提取ip地址 13 string_ip = "is this 289.22.22.22 ip ? 14 result = re.findall(r"(?:[0-9]{1,3}.){3}[0-9]{1,3}", string_ip) 15 if result: 16 print result 17 else: 18 print "re cannot find ip" 19 #精确提取IP 20 result = re.findall(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]?)", string_ip): 21 if result: 22 print result 23 else: 24 print "re cannot find ip
下面是IPv6的正则匹配表达式
1 string_IPv6="1050:0:0:0:5:600:300c:326b" 2 #匹配是否满足IPv6格式要求,请注意例子里大小写不敏感 3 if re.match(r"^(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}$", string_IPv6, re.I): 4 print "IPv6 vaild" 5 else: 6 print "IPv6 invaild" 7 #提取IPv6,例子里大小写不敏感 8 result = re.findall(r"(?<![:.w])(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}(?![:.w])", string_IPv6, re.I) 9 #打印提取结果 10 print result