正则表达式是什么?
正则表达式是一种强大的文本匹配工具,用特殊的字符串模式来匹配、搜索和替换文本。
基本正则语法
import re
# 匹配特定字符
re.match(r'Hello', 'Hello World')
re.search(r'World', 'Hello World')
# 字符类
re.search(r'[abc]', 'banana')
re.search(r'[0-9]', 'abc123')
预定义字符类
| 模式 | 含义 |
|---|---|
| \d | 匹配数字 |
| \D | 匹配非数字 |
| \w | 匹配字母、数字、下划线 |
| \s | 匹配空白字符 |
| . | 匹配任意字符 |
常用函数
# findall: 返回所有匹配
emails = re.findall(r'\\w+@\\w+\\.\\w+', text)
# sub: 替换
new_text = re.sub(r'\\d+', '#', 'abc123def456')
# split: 分割
parts = re.split(r'[,-]', 'a,b-c')
实战案例
1. 验证手机号
phone = '13812345678'
result = re.match(r'^1[3-9]\\d{9}$', phone)
print(result is not None) # True
2. 验证邮箱
email = 'user@example.com'
result = re.match(r'^\\w+@\\w+\\.\\w+$', email)
print(result is not None) # True
3. 提取URL
text = '访问 https://www.example.com 获取更多信息'
urls = re.findall(r'https?://\\S+', text)
print(urls) # ['https://www.example.com']
总结
正则表达式是处理文本的利器。虽然学习曲线有些陡峭,但掌握了它,处理字符串问题会事半功倍。