正则表达式
概述
正则表达式:描述字符串匹配模式的工具,用于验证、提取、替换符合某种模式的文本。
常用元字符
| 符号 |
含义 |
示例 |
. |
任意字符 |
b.t → bat/but/b#t |
\d |
数字 |
\d{11} → 11位数字 |
\w |
字母/数字/下划线 |
\w+ → 单词 |
\s |
空白字符 |
love\syou |
\b |
单词边界 |
\bthe\b |
^ |
字符串开始 |
^Hello |
$ |
字符串结束 |
.exe$ |
[] |
字符集 |
[aeiou] → 元音 |
[^] |
排除字符集 |
[^0-9] → 非数字 |
* |
0次或多次 |
\w* |
+ |
1次或多次 |
\w+ |
? |
0次或1次 |
https? |
{m,n} |
m到n次 |
\d{3,5} |
\| |
或 |
foo\|bar |
re 模块核心函数
import re
| 函数 |
说明 |
re.match() |
从开头匹配,成功返回 Match 对象 |
re.search() |
搜索第一个匹配 |
re.findall() |
找出所有匹配,返回列表 |
re.finditer() |
返回迭代器 |
re.split() |
按模式拆分 |
re.sub() |
替换 |
re.fullmatch() |
完全匹配 |
示例
验证用户名和QQ号
import re
username = input('用户名: ')
qq = input('QQ号: ')
# match:从头匹配
if re.match(r'^[0-9a-zA-Z_]{6,20}$', username):
print('用户名有效')
else:
print('用户名无效')
# fullmatch:完全匹配
if re.fullmatch(r'[1-9]\d{4,11}', qq):
print('QQ号有效')
提取手机号
text = '我的手机号是13512346789,他的号码是15600998765'
# 匹配 1开头 + 3/4/5/7/8 + 11位数字
pattern = re.compile(r'1[34578]\d{9}')
phones = pattern.findall(text)
print(phones) # ['13512346789', '15600998765']
# 更精确的匹配
pattern2 = re.compile(r'(?:\+86)?(1[38]\d{9}|14[57]\d{8}|15[0-35-9]\d{8})')
替换敏感词
text = 'Oh, shit! 你是个傻逼吗?'
cleaned = re.sub(r'fuck|shit|[傻煞沙][逼笔比叉]', '*', text, flags=re.IGNORECASE)
print(cleaned) # Oh, *! 你是*吗?
拆分字符串
poem = '床前明月光,疑是地上霜。举头望明月,低头思故乡。'
sentences = re.split(r'[,。]', poem)
sentences = [s for s in sentences if s]
print(sentences)
# ['床前明月光', '疑是地上霜', '举头望明月', '低头思故乡']
编译复用(性能优化)
# 重复使用同一正则时,先编译
pattern = re.compile(r'\d{4}-\d{2}-\d{2}')
dates = pattern.findall(text)
常用 flags
re.I / re.IGNORECASE # 忽略大小写
re.M / re.MULTILINE # 多行模式
re.S / re.DOTALL # . 匹配换行
总结