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

yipeiwu_com5年前Python基础

Linux

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地址,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

深入了解Python枚举类型的相关知识

枚举类型可以看作是一种标签或是一系列常量的集合,通常用于表示某些特定的有限集合,例如星期、月份、状态等。 Python 的原生类型(Built-in types)里并没有专门的枚举类型,...

Python中的下划线详解

这篇文章讨论Python中下划线_的使用。跟Python中很多用法类似,下划线_的不同用法绝大部分(不全是)都是一种惯例约定。 一、 单个下划线直接做变量名(_) 主要有三种情...

对python 生成拼接xml报文的示例详解

最近临时工作要生成xml报名,通过MQ接口发送。简单小程序。 自增长拼成xml报文 Test_001.py # encoding=utf-8 import time orderI...

Pandas之Dropna滤除缺失数据的实现方法

约定: import pandas as pd import numpy as np from numpy import nan as NaN 滤除缺失数据 pandas的设计目...

在Django的session中使用User对象的方法

在Django的session中使用User对象的方法

通过session,我们可以在多次浏览器请求中保持数据, 接下来的部分就是用session来处理用户登录了。 当然,不能仅凭用户的一面之词,我们就相信,所以我们需要认证。 当然了,Dja...