Python正则表达式匹配和提取IP地址
程序员文章站
2023-12-10 21:00:10
linux
no.1 ipv4
下面是ipv4的ip正则匹配实例:
简单的匹配给定的字符串是否是ip地址
import re
if re.match(r"...
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
总结
以上所述是小编给大家介绍的python正则表达式匹配和提取ip地址,希望对大家有所帮助