Python检测URL中是否包含IP地址的两种正则实现

林舟
林舟
发布时间:2026-10-13 | 6人浏览过
原创

本文介绍在Python中利用re模块检测URL是否包含IP地址的两种正则表达式写法。通过对比自定义的简练模式与网络常见复杂模式,验证两者均能正确提取IP。代码演示了如何遍历URL列表并输出匹配结果,为需要解析链接内容的场景提供参考。

为了检测链接中是否包含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 相关产品和应用

全部下载

专题列表