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

yipeiwu_com5年前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连接mongodb操作数据示例(mongodb数据库配置类)

一、相关代码数据库配置类 MongoDBConn.py 复制代码 代码如下:#encoding=utf-8'''Mongo Conn连接类'''import pymongoclass D...

在Python中关于使用os模块遍历目录的实现方法

一、Python中os模块的常见的使用方法 os.listdir(path):遍历path的文件或者文件夹,返回一个列表 os.path.join(path1,path2,……,path...

Python 获取当前所在目录的方法详解

sys.path 模块搜索路径的字符串列表。由环境变量PYTHONPATH初始化得到。 sys.path[0]是调用Python解释器的当前脚本所在的目录。 sys.argv 一个传给P...

Python面向对象总结及类与正则表达式详解

Python面向对象总结及类与正则表达式详解

Python3 面向对象 --------------------------------------------------------------------------------...

使用python将excel数据导入数据库过程详解

因为需要对数据处理,将excel数据导入到数据库,记录一下过程。 使用到的库:xlrd 和 pymysql (如果需要写到excel可以使用xlwt) 直接丢代码,使用python3...