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

yipeiwu_com6年前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 XlsxWriter模块Chart类用法实例分析

Python XlsxWriter模块Chart类用法实例分析

本文实例讲述了Python XlsxWriter模块Chart类用法。分享给大家供大家参考,具体如下: 一 点睛 Chart类是XlsxWriter模块中图表组件的基类,支持的图表类型包...

Python实现E-Mail收集插件实例教程

Python实现E-Mail收集插件实例教程

__import__函数 我们都知道import是导入模块的,但是其实import实际上是使用builtin函数import来工作的。在一些程序中,我们可以动态去调用函数,如果我们知道...

python隐藏终端执行cmd命令的方法

在用pyinstaller打包后不想要后面的终端命令框,但是打包时加了-w或者--noconsole命令后会导致cmd程序不能运行从而出错。这个时候用subprocess可以解决该类问题...

django 创建过滤器的实例详解

django 创建过滤器 一、需求来源: 假如有一个模板文件有一个字符串变量,这个字符串变量中不能有任何的空格,而恰恰这个模板被很多个视图函数多调用,那么你每次在视图函数中穿这个字符串变...

Python3.6.x中内置函数总结及讲解

Python3.6.x中内置函数总结 # -*- coding:utf-8 -*- """ abs() dict() help() min() s...