在Python中使用正则表达式提取特定格式的文本,核心是设计合适的正则模式,然后利用re模块的函数(如findall()、search()、finditer()等)进行提取。以下是具体步骤和示例:
函数 | 用途 | 返回值 |
|---|---|---|
re.findall() | 提取所有匹配的内容 | 列表(包含所有匹配的字符串) |
re.search() | 提取第一个匹配的内容 | 匹配对象(需用group()获取) |
re.finditer() | 提取所有匹配的内容(返回迭代器) | 迭代器(每个元素是匹配对象) |
邮箱格式特点:用户名@域名.后缀(如user@example.com)
import re
text = "联系我们: abc@qq.com, 工作邮箱: xyz_123@gmail.com, 无效邮箱: test@.com"
# 正则模式:匹配邮箱(用户名允许字母、数字、下划线、点)
pattern = r"\w+(\.\w+)*@[a-zA-Z0-9]+\.[a-zA-Z]{2,}"
# 提取所有邮箱
emails = re.findall(pattern, text)
print(emails)
# 输出:['abc@qq.com', 'xyz_123@gmail.com']手机号格式:11位数字,以1开头,第二位为3-9
import re
text = "张三:13812345678,李四:19987654321,无效号:12345678901"
# 正则模式:匹配手机号
pattern = r"1[3-9]\d{9}"
# 提取所有手机号
phones = re.findall(pattern, text)
print(phones)
# 输出:['13812345678', '19987654321']支持YYYY-MM-DD、YYYY/MM/DD、MM-DD-YYYY等格式
import re
text = "今天是2023-10-05,昨天是2023/10/04,项目截止日:09-30-2023"
# 正则模式:匹配多种日期格式(分组提取年、月、日)
pattern = r"(\d{4})[-/](\d{2})[-/](\d{2})|(\d{2})[-/](\d{2})[-/](\d{4})"
# 用finditer()获取详细匹配信息
matches = re.finditer(pattern, text)
for match in matches:
# 分组1-3对应YYYY-MM-DD,分组4-6对应MM-DD-YYYY
if match.group(1):
print(f"日期: {match.group(1)年}{match.group(2)月}{match.group(3)日}")
else:
print(f"日期: {match.group(6)年}{match.group(4)月}{match.group(5)日}")
# 输出:
# 日期: 2023年10月05日
# 日期: 2023年10月04日
# 日期: 2023年09月30日例如提取<a>标签中的链接和文本
import re
html = '''
<a href="https://www.baidu.com">百度</a>
<a href="https://www.google.com">谷歌</a>
'''
# 正则模式:提取href属性和标签文本(使用非贪婪匹配)
pattern = r'<a href="(.*?)">(.*?)</a>'
# 提取所有链接和文本(返回元组列表)
results = re.findall(pattern, html)
for url, text in results:
print(f"链接: {url}, 文本: {text}")
# 输出:
# 链接: https://www.baidu.com, 文本: 百度
# 链接: https://www.google.com, 文本: 谷歌使用分组():通过()标记需要提取的部分,用group(1)、group(2)等获取(group(0)是完整匹配)
# 提取"姓名:XXX, 年龄:XX"中的姓名和年龄
text = "姓名:张三, 年龄:25"
pattern = r"姓名:(.*?), 年龄:(.*?)"
match = re.search(pattern, text)
print(match.group(1)) # 张三
print(match.group(2)) # 25非贪婪匹配:在*、+后加?,避免匹配范围过大(如.*?匹配尽可能少的字符)
转义特殊字符:对.、*、(等特殊字符,需用\转义(如匹配www.baidu.com中的点,需写为\.)
预编译模式:频繁提取时,用re.compile()编译模式提高效率
pattern = re.compile(r"\d+") # 预编译
print(pattern.findall("A1B2C3")) # ['1', '2', '3']通过以上方法,可以灵活提取各种特定格式的文本。关键是根据目标格式设计精准的正则模式,复杂场景下可逐步测试调整模式。