Python 正则表达式提取电话号码、邮箱地址和 IP 地址
使用 Python 正则表达式提取电话号码、邮箱地址和 IP 地址
本示例代码展示了如何使用 Python 正则表达式从一段文本中提取电话号码、邮箱地址和 IP 地址。
import re
text = '这是几个电话号码:020-37215850,0991-12345678,01-88664521
这是几个邮箱地址:zhangsan@abc.com,lisi@gduf.edu.cn
这是一个IP地址:192.168.2.1'
# 提取电话号码
tel_pattern = re.compile(r'\d{2,3}-\d{7,8}')
tel_list = tel_pattern.findall(text)
print('电话号码:')
for tel in tel_list:
print(tel)
# 提取邮箱地址
email_pattern = re.compile(r'\w+@\w+\.\w+(?:\.\w+)?')
email_list = email_pattern.findall(text)
print('邮箱地址:')
for email in email_list:
print(email)
# 提取IP地址
ip_pattern = re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
ip_list = ip_pattern.findall(text)
print('IP地址:')
for ip in ip_list:
print(ip)
代码解释:
- 导入
re库,用于正则表达式操作。 - 定义一个字符串
text,包含电话号码、邮箱地址和 IP 地址。 - 使用
re.compile()创建三个正则表达式模式:tel_pattern匹配电话号码格式,如020-37215850。email_pattern匹配邮箱地址格式,如zhangsan@abc.com。ip_pattern匹配 IP 地址格式,如192.168.2.1。
- 使用
findall()方法在文本中查找匹配的模式,并返回一个列表。 - 使用循环遍历列表,并打印提取到的电话号码、邮箱地址和 IP 地址。
通过这个例子,我们可以了解如何使用 Python 正则表达式提取特定格式的信息,并通过循环方法进行处理。
原文地址: https://www.cveoy.top/t/topic/mANv 著作权归作者所有。请勿转载和采集!