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

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

本文介绍在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 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。