一、正则表达式核心概念
正则表达式(Regular Expression)是用于字符串匹配的强大工具,通过特定语法描述文本模式。Python通过内置的re
模块提供全面支持,以下是核心语法要素:
1.1 基础元字符
符号 | 含义 | 示例 |
---|---|---|
. |
匹配任意字符(除换行) | r'A..-4..' 匹配 A123-456 |
^ |
匹配字符串开头 | r'^user' 验证用户名前缀 |
$ |
匹配字符串结尾 | r'呢?$' 检查问句结尾 |
* |
0次或多次重复 | r'p*izza' 匹配 pizza /pppppizza |
+ |
1次或多次重复 | r'\w+@\w+\.\w+' 匹配邮箱 |
? |
0次或1次重复 | r'\d?-\d{4}' 匹配可选区号 |
1.2 字符集与量词
# 字符集示例
[abc] # 匹配a/b/c中的一个
[^0-9] # 匹配非数字
\d{3} # 精确匹配3位数字
\d{2,5} # 匹配2-5位数字
1.3 边界与分组
# 单词边界与分组捕获
r'\bPython\b' # 精确匹配单词"Python"
r'(\d{3})-\1+' # 捕获分组并引用(如123-123-123)
二、re模块核心函数详解
Python的re
模块提供6大核心函数,覆盖90%的文本处理场景:
2.1 基础匹配函数
import re
# 精确匹配开头
if re.match(r'^user', 'user123'):
print("用户名合法")
# 全局搜索第一个匹配
match = re.search(r'\d+', '价格是199元')
print(match.group()) # 输出:199
2.2 高级处理函数
# 提取所有匹配项
emails = re.findall(r'\w+@\w+\.\w+', '联系我: a@b.com, c@d.net')
# 文本替换
text = re.sub(r'Python', 'Python编程', '我喜欢Python')
# 分割字符串
parts = re.split(r'[,;]', 'apple,orange;banana')
三、实战案例解析
3.1 邮箱验证器
def validate_email(email):
pattern = r'^[\w.%+-]+@[\w.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))
print(validate_email('test@example.com')) # True
print(validate_email('invalid.email')) # False
3.2 HTML标签提取器
html = "<div>内容1</div><p>内容2</p>"
tags = re.findall(r'<([^>]+)>', html)
print(tags) # 输出:['div', 'p']
3.3 电话号码清洗
def clean_phone(number):
# 提取11位数字并格式化
cleaned = re.sub(r'\D', '', number)
if len(cleaned) == 11:
return f"{cleaned[:3]}-{cleaned[3:7]}-{cleaned[7:]}"
return "无效号码"
print(clean_phone("138-1234-5678")) # 138-1234-5678
四、进阶技巧
4.1 预编译提升性能
# 预编译正则表达式
email_re = re.compile(r'^[\w.%+-]+@[\w.-]+\.[a-zA-Z]{2,}$')
if email_re.match('user@domain.com'):
# 处理逻辑
4.2 命名分组
# 使用命名分组提取URL组件
url_pattern = re.compile(r'^(?P<protocol>https?)://(?P<domain>[^/]+)')
match = url_pattern.match('https://www.example.com')
print(match.group('protocol')) # https
print(match.group('domain')) # www.example.com
4.3 反向引用
# 匹配重复出现的单词
text = "hello hello world"
matches = re.findall(r'\b(\w+)\s+\1\b', text)
print(matches) # ['hello']
五、常见错误处理
5.1 贪婪与非贪婪匹配
# 非贪婪匹配解决过度匹配问题
html = "<a>链接</a><b>标题</b>"
# 使用?开启非贪婪模式
tags = re.findall(r'<.*?>(.*?)</.*?>', html)
print(tags) # ['链接', '标题']
5.2 转义特殊字符
# 匹配包含特殊字符的文本
text = "文件路径: C:\\Users\\Name"
matches = re.findall(r'C:\\\\Users\\\\\w+', text)
print(matches) # ['C:\\Users\\Name']
六、学习资源推荐
- 官方文档:Python re模块文档
- 正则表达式测试工具:RegExr
- 进阶书籍:《精通正则表达式》(第三版)
通过掌握这些核心知识,您可以高效处理90%的文本处理需求。建议从简单案例入手,逐步尝试复杂模式,配合在线测试工具验证正则表达式,快速提升实战能力。