python 匹配url中是否存在IP地址的方法

yipeiwu_com6年前Python基础

因为需要检测一个一个链接中是否包含了IP地址,在这里需要使用到正则表达式 ,python完美的支持了正则表达式,在这里使用re模块来完成,对正则表达式并不是很熟练,每次都是需要用的时候现查一下然后写一下,这里给出来自己的代码以及借鉴别人的匹配模式

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
功能:对于给定的URL,检测其中是否包含IP
'''
import re
def ip_exist_two(one_url):
	compile_rule = re.compile(r'(?<![\.\d])(?:\d{1,3}\.){3}\d{1,3}(?![\.\d])')
	match_list = re.findall(compile_rule, one_url)
	if match_list:
		print match_list
	else:
		print 'missing................'
def ip_exist_one(one_url):
	compile_rule = re.compile(r'\d+[\.]\d+[\.]\d+[\.]\d+') 
	match_list = re.findall(compile_rule, one_url)
	if match_list:
		print match_list
	else:
		print 'missing................'
if __name__ == '__main__':
	ip_list = ['http://101.23.45.67/sd/sd.html','http://www.baidu.com',
	'http://34.54.65.3/dsdfjkk.htm','http://dhj.fdjjd.com/78078979/dsdfjkk.htm']
	for one_url in ip_list:
		ip_exist_one(one_url)
	print '****************************************************'
	for one_url in ip_list:
		ip_exist_two(one_url)

ip_exist_one(one_url)里面是自己的匹配模式,个人感觉更贱练一下,ip_exist_two(one_url)里面是网上提供的匹配IP的正则表达式,感觉比较繁杂一下,不过试验了一下都是可以正确匹配出来结果的。

下面是打印出来的结果

['101.23.45.67']
missing................
['34.54.65.3']
missing................
****************************************************
['101.23.45.67']
missing................
['34.54.65.3']
missing................

以上这篇python 匹配url中是否存在IP地址的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python实现的按要求生成手机号功能示例

本文实例讲述了python实现的按要求生成手机号功能。分享给大家供大家参考,具体如下: 看到一个生成手机号的代码,于是自己优化了一下,可以支持按要求生成手机号。 #!/usr/bin...

Python实现时钟显示效果思路详解

Python实现时钟显示效果思路详解

语言:Python IDE:Python.IDE 1.编写时钟程序,要求根据时间动态更新 2.代码思路 需求:5个Turtle对象, 1个绘制外表盘+3个模拟表上针+1个输出文字...

Python数据类型详解(二)列表

一.基本数据类型   整数:int   字符串:str(注:\t等于一个tab键)   布尔值: bool   列表:list (元素的集合)   列表用[]   元祖:tuple  ...

python模块之subprocess模块级方法的使用

subprocess.run() 运行并等待args参数指定的指令完成,返回CompletedProcess实例。 参数:(*popenargs, input=None, captur...

纯Python开发的nosql数据库CodernityDB介绍和使用实例

纯Python开发的nosql数据库CodernityDB介绍和使用实例

看看这个logo,有些像python的小蛇吧 。这次介绍的数据库codernityDB是纯python开发的。 先前用了下tinyDB这个本地数据库,也在一个api服务中用了下,一开始...