Python正则匹配和提取IP地址

in 互联网技术 with 0 comment  访问: 554 次

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 ip

No.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
WeZan
Responses