python正则表达式(Regular Expression,简称regex或regexp)是一种用于匹配字符串的强大工具,它通过特定的字符组合来描述、匹配一系列符合某个句法规则的字符串。在re模块的支撑下,python正则表达式成为文本处理、数据清洗、爬虫开发等场景中的核心技能。
从基础的字符串查找,到复杂的模式匹配(如邮箱、手机号、IP地址验证),python正则表达式提供了统一而灵活的解决方案。其核心优势在于:
但需注意:python正则表达式并非万能——对于简单字符串匹配(如str.find()),直接使用内置方法更高效;正则表达式适合模式匹配而非逻辑判断。
掌握以下基础语法,即可应对90%的日常匹配需求:
| 语法 | 说明 | 示例 | 匹配内容 |
|---|---|---|---|
. | 匹配任意单字符(不含换行) | gr.y | gray, grey |
\d | 数字字符 | \d\d\d | 123 |
\w | 字母、数字、下划线 | \w+ | user_name |
\s | 空白字符(空格、制表符等) | a\s+b | a b |
\b | 单词边界 | \bpython\b | 匹配完整单词python,避免匹配pythonic |
| 语法 | 说明 | 示例 | 匹配内容 |
|---|---|---|---|
* | 0次或多次 | ab* | a, ab, abb |
+ | 1次或多次 | ab+ | ab, abb(不含a) |
? | 0次或1次 | colou?r | color, colour |
{n} | 恰好n次 | \d{4} | 2023 |
{n,} | 至少n次 | \d{2,} | 12, 1234 |
{n,m} | n到m次 | \d{3,5} | 123, 12345 |
[abc]:匹配a、b或c中的任一字符[a-z]:匹配任意小写字母[^abc]:匹配非a、b、c的字符(取反)[0-9a-fA-F]:匹配十六进制字符注意:在字符集中,特殊字符如.、*失去特殊含义,仅作字面量。但^在开头表示取反,否则仅作普通字符。
| 语法 | 说明 | 示例 | 匹配位置 |
|---|---|---|---|
^ | 行首 | ^http | 以http开头的字符串 |
$ | 行尾 | com$ | 以com结尾的字符串 |
\A | 字符串开头 | \Aabc | 仅匹配整个字符串开头 |
\Z | 字符串结尾 | \Zxyz | 仅匹配整个字符串结尾 |
python正则表达式通过re模块提供核心功能,常用方法如下:
re.match(pattern, string, flags=0)从字符串string的起始位置尝试匹配pattern,返回Match对象或None。
import re
# 匹配开头的数字
result = re.match(r'\d+', '123abc')
print(result.group()) # 输出: 123
# 无法匹配(起始位置非数字)
result = re.match(r'\d+', 'abc123')
print(result) # 输出: None
关键点:仅匹配开头,不支持跨位置查找。若需全局匹配,请用search()或findall()。
re.search(pattern, string, flags=0)扫描整个字符串,返回第一个匹配项的Match对象。
import re
# 搜索任意位置的数字
result = re.search(r'\d+', 'abc123def456')
print(result.group()) # 输出: 123
适合处理非结构化文本(如日志、HTML片段),是爬虫中最常用的方法。
re.findall(pattern, string, flags=0)返回所有匹配项的列表,若含分组则返回分组内容元组列表。
import re
# 提取所有数字
nums = re.findall(r'\d+', 'a1b22c333')
print(nums) # 输出: ['1', '22', '333']
# 含分组时(仅返回分组内容)
emails = re.findall(r'(\w+)@(\w+)\.(\w+)', 'user@test.com admin@domain.org')
print(emails) # 输出: [('user', 'test', 'com'), ('admin', 'domain', 'org')]
re.sub(pattern, repl, string, count=0, flags=0)替换匹配项,返回新字符串。
import re
# 替换手机号中间4位为*
text = '联系我:13812345678或13987654321'
cleaned = re.sub(r'(\d{3})\d{4}(\d{4})', r'\1****\2', text)
print(cleaned) # 输出: 联系我:138****5678或139****4321
技巧:用\1、\2引用分组内容,实现灵活替换。
python正则表达式的分组机制是高级匹配的核心,用于提取子串、实现回溯引用、控制量词范围。
用圆括号()包裹子模式,形成捕获组:
import re
text = 'Date: 2023-08-15'
match = re.search(r'(\d{4})-(\d{2})-(\d{2})', text)
print(match.group(0)) # 全匹配: 2023-08-15
print(match.group(1)) # 第1组: 2023
print(match.group(2)) # 第2组: 08
用(?P命名分组,增强可读性:
import re
match = re.search(r'(?P\d{4})-(?P\d{2})-(?P\d{2})', 'Date: 2023-08-15')
print(match.group('year')) # 输出: 2023
print(match.groupdict()) # 输出: {'year': '2023', 'month': '08', 'day': '15'}
用(?:pattern)避免捕获,提升性能(尤其在大量分组时):
import re
# 匹配HTTP状态码(仅分组控制量词,不捕获)
match = re.search(r'(?:GET|POST|PUT)\s+\d+', 'POST 200 OK')
print(match.group()) # 输出: POST 200
用\1、\2引用已捕获的分组,实现重复模式匹配:
import re
# 匹配连续重复单词
text = 'hello hello world'
match = re.search(r'(\b\w+\b)\s+\1', text)
print(match.group()) # 输出: hello hello
python正则表达式默认采用贪婪模式(匹配尽可能多的字符),而非贪婪模式(匹配尽可能少的字符)通过?后缀切换。
量词如*、+、{n,m}会尽可能多地匹配字符:
import re
text = '<div>content</div>'
match = re.search(r'<.*>', text)
print(match.group()) # 输出: <div>content</div>(匹配到末尾)
问题:匹配了整个标签对,而非单个标签。
在量词后加?切换为非贪婪:
import re
text = '<div>content</div>'
match = re.search(r'<.*?>', text)
print(match.group()) # 输出: <div>(匹配第一个闭合标签)
实战建议:在HTML/XML解析中,优先使用非贪婪模式;但需注意性能影响(尤其嵌套结构)。
结合本地规则与常见邮箱结构:
import re
def validate_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))
print(validate_email('user+tag@example.com')) # True
print(validate_email('invalid.email@')) # False
解析:
[a-zA-Z0-9._%+-]+:匹配本地部分(允许点、加号、下划线等)[a-zA-Z0-9.-]+:匹配域名(允许点、连字符)\.[a-zA-Z]{2,}:匹配顶级域名(至少2位字母)解析查询字符串中的键值对:
import re
url = 'https://example.com/search?q=python&sort=date&limit=10'
params = dict(re.findall(r'(\w+)=([^&]+)', url))
print(params) # 输出: {'q': 'python', 'sort': 'date', 'limit': '10'}
移除标点、保留中英文与数字:
import re
text = '【Python教程】学习正则表达式!(含100+案例)'
cleaned = re.sub(r'[^\w\u4e00-\u9fff]', '', text)
print(cleaned) # 输出: Python教程学习正则表达式含100+案例
关键点:\u4e00-\u9fff匹配中文字符,\w匹配字母数字下划线。
re.match()处理多行文本问题:re.match()仅匹配开头,无法匹配中间行内容。
解决方案:用re.search()或启用re.MULTILINE标志(^匹配每行开头)。
import re
text = 'Line 1\nLine 2\nLine 3'
# 错误:re.match(r'Line 2', text) 返回None
# 正确:re.search(r'^Line 2', text, re.MULTILINE).group() → 'Line 2'
在模式中直接使用.、?等会导致意外匹配:
import re
# 错误:re.match(r'1.2', '1.2') 也能匹配'1a2'
# 正确:re.match(r'1\.2', '1.2') → 仅匹配字面量'1.2'
在Python 2中需用u'pattern';Python 3默认Unicode,但需确保字符串为str类型:
# Python 3中正确
re.match(r'中文', '中文测试') # ✅
# 若字符串含字节(bytes),需先解码
re.match(r'中文', '中文测试'.encode('utf-8')) # ❌ 错误!
re.compile()提升性能re.VERBOSE标志:添加注释与换行,提升可读性str方法替代正则(如startswith())import re
# 预编译模式
pattern = re.compile(r'\d{4}-\d{2}-\d{2}', re.VERBOSE)
# 添加注释增强可读性
pattern_verbose = re.compile(r"""
(\d{4}) # 年份
- # 分隔符
(\d{2}) # 月份
- # 分隔符
(\d{2}) # 日期
""", re.VERBOSE)