Python 中如何使用 re 模块进行正则表达式处理?
·
正则表达式(Regular Expression, regex) 是一种强大的字符串匹配和处理工具,广泛用于文本搜索、数据提取、格式验证等场景。Python 提供了 re 模块,用于处理正则表达式,支持模式匹配、替换、分割、查找等操作。本文将详细介绍 re 模块的常见用法,包括 匹配字符串、查找模式、替换内容、分割字符串 等,并结合实际案例,帮助你掌握 Python 中的正则表达式处理技巧。
1. re 模块简介
在 Python 中,re 模块提供了丰富的正则表达式功能:
| 方法 | 作用 |
|---|---|
re.match() | 从字符串开头匹配正则表达式 |
re.search() | 在整个字符串中搜索匹配项 |
re.findall() | 查找所有匹配项,返回列表 |
re.finditer() | 查找所有匹配项,返回迭代器 |
re.sub() | 替换匹配内容 |
re.split() | 按匹配项拆分字符串 |
re.compile() | 预编译正则表达式,提高匹配效率 |
📌 核心概念:
match()只匹配字符串开头,失败返回None。search()在整个字符串查找第一个匹配项。findall()返回所有匹配结果(列表)。sub()用于替换字符串中的匹配项。
2. 正则表达式基础语法
| 符号 | 说明 | 示例 |
|---|---|---|
. | 任意字符(除换行) | a.b 可匹配 acb、a1b |
\d | 数字(0-9) | \d+ 可匹配 123 |
\w | 字母、数字、下划线 | \w+ 可匹配 abc_123 |
\s | 空白字符(空格、换行、制表符) | \s+ 可匹配 " " |
^ | 匹配行首 | ^Hello 只能匹配 "Hello world",但不匹配 "A Hello" |
$ | 匹配行尾 | world$ 只能匹配 "Hello world" |
* | 匹配前面字符0次或多次 | a*b 可匹配 b、ab、aaab |
+ | 匹配前面字符1次或多次 | a+b 可匹配 ab、aaab,但不匹配 b |
? | 匹配前面字符0次或1次 | colou?r 可匹配 color 或 colour |
{m,n} | 匹配 m 到 n 次 | a{2,4} 可匹配 aa、aaa、aaaa |
| ` | ` | 或(匹配左或右) |
() | 分组匹配 | (abc)+ 可匹配 abc、abcabc |
3. 使用 re.match() 从开头匹配
match() 方法检查字符串开头是否匹配指定模式:
import re
pattern = r"Hello"
text = "Hello, world!"
match = re.match(pattern, text)
if match:
print("匹配成功:", match.group()) # Hello
else:
print("匹配失败")
📌 特点:
- 只匹配字符串开头,否则返回
None。
4. 使用 re.search() 在字符串中查找模式
search() 可在整个字符串中查找匹配项:
pattern = r"\d+"
text = "今天的温度是 23°C"
match = re.search(pattern, text)
if match:
print("找到匹配:", match.group()) # 23
📌 特点:
- 只返回第一个匹配项。
5. 使用 re.findall() 查找所有匹配项
findall() 返回所有匹配项的列表:
pattern = r"\d+"
text = "今天的温度是 23°C,湿度 80%"
matches = re.findall(pattern, text)
print(matches) # ['23', '80']
📌 适用于:
- 提取多个数据(如所有数字、所有邮箱)。
6. 使用 re.finditer() 获取迭代器
finditer() 返回所有匹配项的迭代器:
pattern = r"\d+"
text = "今天的温度是 23°C,湿度 80%"
matches = re.finditer(pattern, text)
for match in matches:
print("匹配项:", match.group())
📌 适用于:
- 逐个遍历匹配项,支持
.start()、.end()获取位置。
7. 使用 re.sub() 替换字符串
sub() 方法替换匹配的内容:
pattern = r"\d+"
text = "今天的温度是 23°C"
new_text = re.sub(pattern, "XX", text)
print(new_text) # 今天的温度是 XX°C
📌 适用于:
- 数据脱敏(如隐藏电话号码、邮箱)。
8. 使用 re.split() 拆分字符串
split() 按匹配项拆分字符串:
pattern = r"\s+"
text = "Hello World Python"
words = re.split(pattern, text)
print(words) # ['Hello', 'World', 'Python']
📌 适用于:
- 按空格、标点符号、换行符拆分文本。
9. 使用 re.compile() 预编译正则表达式
compile() 提高匹配效率:
pattern = re.compile(r"\d+") # 预编译
text = "价格:100 元"
match = pattern.search(text)
print(match.group()) # 100
📌 适用于:
- 多次匹配时,避免重复解析正则表达式。
10. 实战案例
案例 1:验证手机号
pattern = r"^1[3-9]\d{9}$"
phone = "13912345678"
if re.match(pattern, phone):
print("手机号有效")
else:
print("手机号无效")
案例 2:提取邮件地址
pattern = r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+"
text = "请联系 support@example.com 或 admin@company.com"
emails = re.findall(pattern, text)
print(emails) # ['support@example.com', 'admin@company.com']
案例 3:提取 HTML 标签内的文本
pattern = r"<title>(.*?)</title>"
html = "<html><head><title>Python 正则表达式</title></head></html>"
match = re.search(pattern, html)
if match:
print(match.group(1)) # Python 正则表达式
11. 结论
| 操作 | 方法 |
|---|---|
| 从开头匹配 | re.match() |
| 搜索字符串 | re.search() |
| 查找所有匹配项 | re.findall() |
| 替换内容 | re.sub() |
| 拆分字符串 | re.split() |
| 预编译正则 | re.compile() |
Python re 模块提供了强大的字符串匹配与处理功能,掌握这些方法,可以让你在数据提取、文本分析、格式验证等任务中更加高效!🚀
📌 有什么问题和经验想分享?欢迎在评论区交流、点赞、收藏、关注! 🎯
更多推荐



所有评论(0)