系列说明:正则表达式是"用模式描述字符串"的语言,几乎所有编程语言都支持。它强大到能一行代码完成复杂文本处理,也危险到能让程序卡死(灾难性回溯)。
本篇从零讲透
re模块,先建立正确的心智模型,再逐项讲语法,最后用大量真实案例巩固。学完你能独立写出邮箱、手机号、url、日志解析等常见正则,并知道怎么避免踩坑。
一、为什么需要正则表达式
1.1 没有正则的痛苦
需求:从一段文本里提取所有邮箱地址。
用字符串方法手写:
text = "联系 a@example.com 或 bob.smith@company.org,也可以发到 info@site.com.cn" # 手写提取邮箱?几乎不可能写对 # - @ 前后各有哪些字符? # - 域名有几级? # - 有没有连字符、下划线、加号?
用正则:
import re emails = re.findall(r"[\w.+-]+@[\w-]+\.[\w.-]+", text) print(emails) # ['a@example.com', 'bob.smith@company.org', 'info@site.com.cn']
再比如:
- 校验手机号格式
- 从 html 中提取所有链接
- 解析日志行
2024-01-15 10:30:25 error [module] message - 清洗文本中多余的空白和标点
- 批量替换变量名、格式化代码
这些用字符串方法写会非常啰嗦、容易出错。正则用模式描述规则,代码短、可复用、表达力强。
1.2 正则的定位
| 工具 | 适合 | 不适合 |
|---|---|---|
str.split / replace / find | 简单固定分隔符 | 复杂模式 |
正则 re | 模式匹配、提取、替换 | 解析嵌套结构(html/json/xml) |
| 专用解析器 | html、json、yaml、sql | 简单文本处理 |
⚠️ 重要提醒:不要用正则解析 html/json/xml。这些结构有嵌套、转义、注释,正则无法正确解析。用
beautifulsoup、json、lxml等专用库。正则只适合扁平、有规律的字符串。
二、正则基础语法
2.1 第一个正则
import re
text = "我的电话是 13812345678,备用 13987654321"
# 找所有 11 位数字
result = re.findall(r"\d{11}", text)
print(result) # ['13812345678', '13987654321']r"..."是原始字符串,让\不被 python 转义(写正则必须用)\d匹配一个数字{11}表示"重复 11 次"
2.2 字符匹配:最基础的规则
| 模式 | 含义 | 示例 |
|---|---|---|
. | 任意字符(默认不含换行) | a.c 匹配 abc、a1c、a c |
\d | 数字 [0-9] | \d\d 匹配 42 |
\d | 非数字 | 匹配字母、符号 |
\w | 单词字符 [a-za-z0-9_](含中文) | \w+ 匹配 hello、变量1、中文 |
\w | 非单词字符 | 匹配空格、标点 |
\s | 空白字符(空格、\t、\n、\r) | \s+ 匹配连续空白 |
\s | 非空白字符 | — |
[...] | 字符集合 | [abc] 匹配 a/b/c 之一 |
[^...] | 排除集合 | [^0-9] 匹配非数字 |
示例:
import re # \d:数字 print(re.findall(r"\d+", "abc123def456")) # ['123', '456'] # \w:单词字符(字母、数字、下划线、中文) print(re.findall(r"\w+", "hello 世界 123")) # ['hello', '世界', '123'] # \s:空白 print(re.findall(r"\s+", "a b\tc\nd")) # [' ', '\t', '\n'] # .:任意字符 print(re.findall(r"a.c", "abc a1c a c a\nc")) # ['abc', 'a1c', 'a c'] # [abc]:字符集合 print(re.findall(r"[aeiou]", "hello world")) # ['e', 'o', 'o'] # [^...]:排除 print(re.findall(r"[^0-9]+", "a1b2c3")) # ['a', 'b', 'c']
2.3 字符集合[...]的细节
# 范围 re.findall(r"[a-z]+", "hello world") # ['ello', 'orld'] re.findall(r"[a-za-z]+", "hello world") # ['hello', 'world'] re.findall(r"[0-9a-fa-f]+", "颜色 #ff8800") # ['ff8800'] # 组合 re.findall(r"[aeiou0-9]+", "a1e2i3") # ['a1e2i3'] # 排除 re.findall(r"[^aeiou\s]+", "hello world") # ['h', 'll', 'w', 'rld'] # 在集合中,大部分元字符失去特殊含义 re.findall(r"[.+*]", "a.b+c*d") # ['.', '+', '*'] # 但 ] \ ^ - 需要小心 re.findall(r"[\]\\]", "a]b\\c") # [']', '\\']
实用速记:
[abc]:a 或 b 或 c[a-z]:小写字母[a-za-z]:所有字母[0-9a-fa-f]:十六进制字符[^abc]:除 a、b、c 外的任意字符
2.4 预定义字符类速查
| 写法 | 等价于 | 记忆 |
|---|---|---|
\d | [0-9] | digit 数字 |
\d | [^0-9] | 大写是取反 |
\w | [a-za-z0-9_] | word 单词字符 |
\w | [^a-za-z0-9_] | 大写是取反 |
\s | [ \t\n\r\f\v] | space 空白 |
\s | [^ \t\n\r\f\v] | 大写是取反 |
\w能匹配中文!因为 python 3 的\w默认是 unicode 感知的。如果不希望匹配中文,用[a-za-z0-9_]或加re.ascii标志。
2.5 量词:控制重复次数
| 量词 | 含义 | 示例 |
|---|---|---|
* | 0 次或多次 | a* 匹配 ``、a、aaa |
+ | 1 次或多次 | a+ 匹配 a、aaa |
? | 0 次或 1 次 | a? 匹配 ``、a |
{n} | 恰好 n 次 | a{3} 匹配 aaa |
{n,} | 至少 n 次 | a{2,} 匹配 aa、aaa |
{n,m} | n 到 m 次 | a{2,4} 匹配 aa、aaa、aaaa |
import re
print(re.findall(r"a*", "aaa")) # ['aaa', ''] 注意末尾空串
print(re.findall(r"a+", "aaa b aa")) # ['aaa', 'aa']
print(re.findall(r"colou?r", "color colour")) # ['color', 'colour']
print(re.findall(r"\d{3}", "12 123 1234")) # ['123', '123']
print(re.findall(r"\d{2,4}", "1 12 123 12345")) # ['12', '123', '1234', '5']量词修饰的是"前面的一个原子":
# ab+ 表示 a 后面跟一个或多个 b,不是 (ab) 重复 re.findall(r"ab+", "ab abb abbb") # ['ab', 'abb', 'abbb'] # (ab)+ 表示 ab 这个整体重复 re.findall(r"(ab)+", "ab abb abab") # ['ab', 'ab', 'ab']
2.6 锚点:匹配位置
| 锚点 | 含义 |
|---|---|
^ | 字符串开头(多行模式下是行首) |
$ | 字符串结尾(多行模式下是行尾) |
\a | 字符串开头(不受多行模式影响) |
\z | 字符串结尾(不受多行模式影响) |
\b | 单词边界 |
\b | 非单词边界 |
import re print(re.findall(r"^\d+", "123 abc")) # ['123'] print(re.findall(r"\d+$", "abc 123")) # ['123'] # 单词边界:\b 在"单词字符"和"非单词字符"之间 re.findall(r"\bcat\b", "cat concat cats cat.") # ['cat', 'cat'] # 对比:不用 \b re.findall(r"cat", "cat concat cats") # ['cat', 'cat', 'cat'] # 找以 python 开头的单词 re.findall(r"\bpython\w*", "python3 pythonic java python") # ['python3', 'pythonic', 'python']
^ 和 $ 在 re.m(多行模式)下的区别:
text = "line1\nline2\nline3" # 默认:^ 只匹配字符串开头 print(re.findall(r"^\w+", text)) # ['line1'] # 多行模式:^ 匹配每行开头 print(re.findall(r"^\w+", text, re.m)) # ['line1', 'line2', 'line3'] # $ 同理 print(re.findall(r"\w+$", text)) # ['line3'] print(re.findall(r"\w+$", text, re.m)) # ['line1', 'line2', 'line3']
2.7 选择:|
# a|b 表示 a 或 b re.findall(r"cat|dog", "cat dog bird cat") # ['cat', 'dog', 'cat'] # 分组配合选择 re.findall(r"(cat|dog)s?", "cats dog dogs") # ['cat', 'dog', 'dog'] # ⚠️ 注意:| 优先级最低,不加括号容易出错 # a|bc 是 (a) 或 (bc),不是 a 或 b 后跟 c re.findall(r"a|bc", "abc") # ['a', 'bc']
2.8 转义:匹配特殊字符本身
元字符在正则里有特殊含义,要匹配它们本身,需要加 \:
# 元字符:. ^ $ * + ? { } [ ] \ | ( )
# 匹配真正的点(不是"任意字符")
re.findall(r"\d+\.\d+", "3.14 和 2.71") # ['3.14', '2.71']
# 匹配真正的问号
re.findall(r"为什么\?", "为什么? 因为...") # ['为什么?']
# 匹配真正的加号
re.findall(r"a\+b", "a+b aab") # ['a+b']re.escape() 自动转义:
import re # 不确定字符串里有什么特殊字符时,用 escape 自动转义 keyword = "c++ (编程)" pattern = re.escape(keyword) print(pattern) # c\+\+\ \(编程\) print(re.search(pattern, "我爱 c++ (编程)")) # 常用于把用户输入安全地拼进正则 user_input = "a.b*c" safe_pattern = re.escape(user_input)
三、re模块的核心函数
3.1 六大函数速查
| 函数 | 作用 | 返回 |
|---|---|---|
re.match(p, s) | 从字符串开头匹配 | match 或 none |
re.search(p, s) | 在任意位置找第一个匹配 | match 或 none |
re.findall(p, s) | 找所有匹配 | 列表(字符串或元组) |
re.finditer(p, s) | 找所有匹配 | 迭代器,元素是 match |
re.sub(p, repl, s) | 替换 | 新字符串 |
re.split(p, s) | 按模式拆分 | 列表 |
编译版本:re.compile(p) 得到 pattern 对象,之后调用 .match / .search 等方法,适合反复使用同一个模式。
3.2match:从开头匹配
import re # match 必须从字符串开头匹配 m = re.match(r"\d+", "123abc") print(m) # <re.match object; span=(0, 3), match='123'> print(m.group()) # '123' # 不是开头就返回 none m = re.match(r"\d+", "abc123") print(m) # none # 注意:match 是"开头匹配",不是"完全匹配" m = re.match(r"\d+", "123abc") print(m.group()) # '123' 只要开头匹配就行
**想"完全匹配"**用 fullmatch 或加 \z:
# fullmatch:整个字符串必须完全匹配 print(re.fullmatch(r"\d+", "123")) # <re.match ...> print(re.fullmatch(r"\d+", "123abc")) # none # 等价写法:加 $ 或 \z print(re.match(r"\d+$", "123")) # <re.match ...>
3.3search:任意位置找第一个
import re m = re.search(r"\d+", "abc123def456") print(m.group()) # '123' print(m.start(), m.end()) # 3 6
match vs search 对比:
text = "abc123" re.match(r"\d+", text) # none(开头不是数字) re.search(r"\d+", text) # match '123' re.match(r"abc", text) # match 'abc' re.search(r"abc", text) # match 'abc'
| 函数 | 从哪开始 |
|---|---|
match | 只从开头 |
search | 任意位置 |
记忆:
match严格,只认开头;search宽松,到处找。
3.4findall:找所有
import re
# 返回字符串列表(无分组时)
print(re.findall(r"\d+", "a1 b22 c333")) # ['1', '22', '333']
# 有 1 个分组时,返回分组内容的列表
print(re.findall(r"(\d+)", "a1 b22 c333")) # ['1', '22', '333']
# 有多个分组时,返回元组列表
print(re.findall(r"(\w+)=(\w+)", "a=1 b=2"))
# [('a', '1'), ('b', '2')]
# 匹配结果里没有就返回空列表
print(re.findall(r"\d+", "no digits")) # []⚠️ findall 有分组时的坑:
# 无分组:完整匹配 print(re.findall(r"\d+", "a1 b22")) # ['1', '22'] # 一个分组:返回分组内容,不是完整匹配! print(re.findall(r"a(\d+)", "a1 b22 a333")) # ['1', '333'] # 想要完整匹配又要有分组:用非捕获分组 (?:...) print(re.findall(r"a(?:\d+)", "a1 b22 a333")) # ['a1', 'a333']
3.5finditer:返回 match 对象迭代器
需要位置信息或需要按需处理时用 finditer:
import re
for m in re.finditer(r"\d+", "a1 b22 c333"):
print(f"'{m.group()}' at {m.start()}-{m.end()}")
# '1' at 1-2
# '22' at 4-6
# '333' at 8-11finditer 不一次性返回所有结果,内存友好,适合大文本。
3.6sub:替换
import re
# 基本替换
print(re.sub(r"\d+", "#", "a1 b22 c333")) # 'a# b# c#'
# 限制替换次数
print(re.sub(r"\d+", "#", "a1 b22 c333", count=2)) # 'a# b# c333'
# 用函数做替换(动态替换)
def double(m):
return str(int(m.group()) * 2)
print(re.sub(r"\d+", double, "a1 b22 c333")) # 'a2 b44 c666'
# 用分组引用做替换
print(re.sub(r"(\w+)@(\w+)", r"\2@\1", "user@server"))
# 'server@user' 交换
# \1 \2 引用分组;也可以写成 \g<1>,更清晰
print(re.sub(r"(\d{4})-(\d{2})-(\d{2})", r"\1年\2月\3日", "2024-01-15"))
# '2024年01月15日'subn:同时返回替换后的字符串和替换次数:
result, count = re.subn(r"\d+", "#", "a1 b22") print(result, count) # 'a# b#' 2
3.7split:按模式拆分
import re # 按多个分隔符拆分 print(re.split(r"[,;\s]+", "a,b; c d")) # ['a', 'b', 'c', 'd'] # 按固定长度拆分 print(re.split(r"\s+", "hello world python")) # ['hello', 'world', 'python'] # 限制拆分次数 print(re.split(r"\s+", "a b c d", maxsplit=2)) # ['a', 'b', 'c d'] # 如果模式有分组,分组内容会出现在结果中! print(re.split(r"(,|;)", "a,b;c")) # ['a', ',', 'b', ';', 'c']
3.8compile:预编译模式
如果一个模式反复使用,预编译能提升性能并让代码更清晰:
import re
# 不预编译:每次调用都会重新编译模式
for text in ["a1", "b2", "c3"]:
re.findall(r"\d+", text)
# 预编译:只编译一次
pattern = re.compile(r"\d+")
for text in ["a1", "b2", "c3"]:
pattern.findall(text)
# 带标志位
date_pattern = re.compile(r"(\d{4})-(\d{2})-(\d{2})")
m = date_pattern.search("日期:2024-01-15")
print(m.groups()) # ('2024', '01', '15')pattern 对象的方法和 re 函数一一对应:
p = re.compile(r"\d+")
p.match("123abc") # 等价于 re.match(r"\d+", "123abc")
p.search("abc123") # 等价于 re.search(...)
p.findall("a1 b22") # 等价于 re.findall(...)
p.finditer("a1 b22") # 等价于 re.finditer(...)
p.sub("#", "a1 b22") # 等价于 re.sub(...)
p.split("a1b22c") # 等价于 re.split(...)
p.fullmatch("123") # 等价于 re.fullmatch(...)性能提示:短小的模式直接调用
re.xxx即可,python 内部有缓存。只有当模式很长、使用频率很高时,re.compile才有明显收益。
四、match 对象
match、search、finditer、fullmatch 返回的都是 match 对象。它保存了匹配的详细信息。
4.1 常用方法
import re
m = re.search(r"(\d{4})-(\d{2})-(\d{2})", "日期:2024-01-15")
print(m.group()) # '2024-01-15' 整个匹配
print(m.group(0)) # '2024-01-15' 同上
print(m.group(1)) # '2024' 第一个分组
print(m.group(2)) # '01'
print(m.group(3)) # '15'
print(m.groups()) # ('2024', '01', '15') 所有分组
print(m.start()) # 3 匹配开始位置
print(m.end()) # 13 匹配结束位置(不包含)
print(m.span()) # (3, 13)
print(m.string) # '日期:2024-01-15' 原始字符串group() 可以一次取多个:
print(m.group(1, 2)) # ('2024', '01')分组可以嵌套:
m = re.match(r"((\d+)-(\d+))", "12-34")
print(m.group()) # '12-34'
print(m.group(1)) # '12-34' 外层分组
print(m.group(2)) # '12' 内层第一个
print(m.group(3)) # '34'
print(m.groups()) # ('12-34', '12', '34')4.2 命名分组
给分组起名字,通过名字访问,可读性更好:
import re
pattern = r"(?p<year>\d{4})-(?p<month>\d{2})-(?p<day>\d{2})"
m = re.search(pattern, "日期:2024-01-15")
print(m.group("year")) # '2024'
print(m.group("month")) # '01'
print(m.group("day")) # '15'
# groupdict:分组名到值的字典
print(m.groupdict())
# {'year': '2024', 'month': '01', 'day': '15'}命名分组在 sub 中的用法:
pattern = r"(?p<year>\d{4})-(?p<month>\d{2})-(?p<day>\d{2})"
result = re.sub(pattern, r"\g<year>年\g<month>月\g<day>日", "2024-01-15")
print(result) # '2024年01月15日'
命名分组在 findall 中仍返回元组:
# 有多个分组时返回元组列表,按分组顺序
matches = re.findall(r"(?p<key>\w+)=(?p<value>\w+)", "a=1 b=2")
print(matches) # [('a', '1'), ('b', '2')]
4.3 非捕获分组(?:...)
普通分组会捕获内容(进入 group() 和 findall 结果)。如果只是想分组应用量词,不希望被捕获,用 (?:...):
# 捕获分组:findall 返回分组内容 print(re.findall(r"(ab)+", "ababab")) # ['ab'] # 非捕获分组:findall 返回完整匹配 print(re.findall(r"(?:ab)+", "ababab")) # ['ababab'] # 示例:提取完整字符串,但分组只用于量词 # 匹配 "a" 后跟至少一个 "bc" print(re.findall(r"a(?:bc)+", "a abc abcbc")) # ['abc', 'abcbc']
典型场景:想提取整体,但内部需要分组:
# 提取带引号的字符串内容,引号可以是单引号或双引号 text = 'name = "张三", age = \'20\'' # ❌ 用捕获分组:返回的是分组内容 print(re.findall(r'[\'"]([^\'"]+)[\'"]', text)) # ['张三', '20'] # 但也可能你就想匹配完整引号(包括引号),用非捕获 print(re.findall(r'[\'"](?:[^\'"]+)[\'"]', text)) # ['"张三"', "'20'"]
4.4 后向引用
引用前面分组匹配的内容,可以匹配重复的内容:
import re # \1 表示"和第一个分组匹配到的内容相同" # 匹配连续重复的单词 text = "hello hello world world python" print(re.findall(r"\b(\w+)\s+\1\b", text)) # ['hello', 'world'] # 匹配重复的字符:aa, bb, cc 这种 print(re.findall(r"(.)\1", "aabbccdd")) # ['a', 'b', 'c', 'd'] # 匹配 html 标签(同名)—— 简易示例,真实 html 用解析器 html = "<b>粗体</b> <i>斜体</i> <b>错的</i>" print(re.findall(r"<(\w+)>.*?</\1>", html)) # ['b', 'i'] 不会匹配 <b>错的</i>
实际用途:去除重复字符、检查成对符号、查找重复单词。不要用它解析嵌套 html。
五、贪婪 vs 非贪婪
5.1 贪婪量词(默认)
*、+、?、{n,m} 默认是贪婪的:能匹配多少就匹配多少。
import re text = "<b>粗体</b><i>斜体</i>" # 贪婪:.* 会尽可能多地匹配 m = re.search(r"<.*>", text) print(m.group()) # '<b>粗体</b><i>斜体</i>' 匹配了整段!
5.2 非贪婪(懒惰)量词
在量词后加 ? 变成非贪婪:能少匹配就少匹配。
# 非贪婪:.*? 尽量少匹配 m = re.search(r"<.*?>", text) print(m.group()) # '<b>' # 找所有标签 print(re.findall(r"<.*?>", text)) # ['<b>', '</b>', '<i>', '</i>']
5.3 对比表
| 贪婪 | 非贪婪 | 含义 |
|---|---|---|
* | *? | 0 次或多次 |
+ | +? | 1 次或多次 |
? | ?? | 0 次或 1 次 |
{n,m} | {n,m}? | n 到 m 次 |
import re text = '"a" 和 "b" 和 "c"' # 贪婪:匹配到最后一个引号 print(re.findall(r'".*"', text)) # ['"a" 和 "b" 和 "c"'] # 非贪婪:每次匹配到最近的引号 print(re.findall(r'".*?"', text)) # ['"a"', '"b"', '"c"']
5.4 什么时候用贪婪,什么时候用非贪婪
- 贪婪:想匹配最长的整体,比如匹配整行、整个块
- 非贪婪:想逐段匹配,比如 html 标签、引号内容、括号内容
# 提取所有括号内容 text = "a(1) b(2) c(3)" # 非贪婪:正确 print(re.findall(r"\(.*?\)", text)) # ['(1)', '(2)', '(3)'] # 贪婪:错误 print(re.findall(r"\(.*\)", text)) # ['(1) b(2) c(3)']
实用建议:不确定时,优先用非贪婪。
.*?通常能得到你想要的结果。
六、断言:不消费字符的条件
断言(lookaround)用来表达"当前位置前/后必须满足某条件",但不消耗字符。
6.1 四种断言
| 语法 | 名称 | 含义 |
|---|---|---|
(?=...) | 正向先行断言 | 后面必须是 … |
(?!...) | 负向先行断言 | 后面不能是 … |
(?<=...) | 正向后行断言 | 前面必须是 … |
(?<!...) | 负向后行断言 | 前面不能是 … |
记忆:
=是"必须"(肯定),!是"不能"(否定);?=/?!是向前看(lookahead),?<=/?<!是向后看(lookbehind)。
6.2 先行断言
import re # 匹配后面跟着 .com 的单词 print(re.findall(r"\w+(?=\.com)", "google.com baidu.cn abc.com")) # ['google', 'abc'] # 匹配后面不跟 .com 的单词 print(re.findall(r"\w+(?!\.com)", "google.com baidu.cn abc.com")) # 注意:结果可能有点绕,因为 \w+(?!\.com) 可以从任意位置回退 # 通常需要配合 \b 使用 # 更好的写法:单词边界 print(re.findall(r"\b\w+(?!\.com\b)\b", "google.com baidu.cn abc.com")) # ['baidu', 'cn']
实用例子:提取密码中的"数字后跟字母"部分:
# 匹配字母后面必须跟数字的位置 text = "a1 b2 c d3" print(re.findall(r"[a-z](?=\d)", text)) # ['a', 'b', 'd']
6.3 后行断言
import re # 匹配前面是 $ 的数字(提取金额) print(re.findall(r"(?<=\$)\d+", "价格 $100 和 $200")) # ['100', '200'] # 匹配前面不是 $ 的数字 print(re.findall(r"(?<!\$)\b\d+", "编号 123 价格 $456")) # ['123']
后行断言的限制:(?<=...) 里的内容必须是固定长度,不能有 *、+、{n,} 等不定长量词:
# ❌ 报错:look-behind requires fixed-width pattern # re.findall(r"(?<=\d+)\w", "abc123") # ✅ 固定长度可以 re.findall(r"(?<=\d\d)\w", "a12b") # ['b']
这是 python 的限制(java、.net 没这个限制)。遇到不定长的情况,改用
\d+([a-z])加分组提取。
6.4 断言的典型应用
应用 1:给数字加千分位
import re
def add_thousands(n):
return re.sub(r"(?<=\d)(?=(\d{3})+$)", ",", str(n))
print(add_thousands(1234567)) # '1,234,567'
print(add_thousands(1000000)) # '1,000,000'
print(add_thousands(123)) # '123'应用 2:同时匹配前后条件
# 匹配被方括号包围的内容 text = "[hello] world [python]" print(re.findall(r"(?<=\[)\w+(?=\])", text)) # ['hello', 'python']
应用 3:密码强度检查
# 检查密码:至少 8 位,包含数字和字母
passwords = ["abc12345", "12345678", "abcdefgh", "a1b2c3d4"]
for pwd in passwords:
if (len(pwd) >= 8
and re.search(r"\d", pwd)
and re.search(r"[a-za-z]", pwd)):
print(f"✓ {pwd}")
else:
print(f"✗ {pwd}")
# ✓ abc12345
# ✗ 12345678
# ✗ abcdefgh
# ✓ a1b2c3d4应用 4:提取不重叠的内容
# 提取 "价格:xxx 元" 中的数字,前面是"价格:" text = "价格:100 元,价格:200 元,售价:300 元" print(re.findall(r"(?<=价格:)\d+", text)) # ['100', '200']
七、标志位(flags)
标志位改变正则的匹配行为。
| 标志 | 简写 | 作用 |
|---|---|---|
re.ignorecase | re.i | 忽略大小写 |
re.multiline | re.m | ^ 和 $ 匹配每行首尾 |
re.dotall | re.s | . 匹配包括换行在内的任意字符 |
re.verbose | re.x | 允许在正则中写注释和空白 |
re.ascii | re.a | \w、\d、\s 只匹配 ascii |
re.unicode | re.u | 默认行为,\w 匹配 unicode |
多个标志用 | 组合:
re.findall(r"pattern", text, re.i | re.m)
7.1re.i忽略大小写
import re
print(re.findall(r"python", "python python python", re.i))
# ['python', 'python', 'python']
# 编译时也可以加
pattern = re.compile(r"python", re.i)
print(pattern.findall("python python"))7.2re.m多行模式
import re text = """line1 line2 line3""" # 默认:^ 只匹配字符串开头 print(re.findall(r"^\w+", text)) # ['line1'] # re.m:^ 匹配每行开头 print(re.findall(r"^\w+", text, re.m)) # ['line1', 'line2', 'line3']
典型应用:处理日志文件,匹配每行开头的日期:
logs = """2024-01-15 10:00:00 info start
2024-01-15 10:01:00 error fail
2024-01-15 10:02:00 info done"""
dates = re.findall(r"^\d{4}-\d{2}-\d{2}", logs, re.m)
print(dates) # ['2024-01-15', '2024-01-15', '2024-01-15']7.3re.s让.匹配换行
import re text = "start\nmiddle\nend" # 默认:. 不匹配换行 print(re.findall(r"start.*end", text)) # [] # re.s:. 匹配包括换行 print(re.findall(r"start.*end", text, re.s)) # ['start\nmiddle\nend'] # 非贪婪版 print(re.findall(r"start.*?end", text, re.s)) # ['start\nmiddle\nend']
7.4re.x详细模式:让长正则可读
复杂正则可以分行写、加注释:
import re
# ❌ 一长串,可读性差
pattern = r"^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})\s+(\w+)"
# ✅ 详细模式:可分行、可注释
pattern = re.compile(r"""
^(\d{4})-(\d{2})-(\d{2}) # 日期 yyyy-mm-dd
\s+ # 空格
(\d{2}):(\d{2}):(\d{2}) # 时间 hh:mm:ss
\s+ # 空格
(\w+) # 日志级别
""", re.x)
m = pattern.match("2024-01-15 10:30:25 error")
print(m.groups()) # ('2024', '01', '15', '10', '30', '25', 'error')写超过 30 个字符的正则,强烈建议用
re.x拆行加注释,否则一周后自己都看不懂。
7.5re.a只匹配 ascii
import re # 默认 \w 匹配中文 print(re.findall(r"\w+", "hello 世界")) # ['hello', '世界'] # re.a:只匹配 ascii print(re.findall(r"\w+", "hello 世界", re.a)) # ['hello']
八、性能陷阱:灾难性回溯
8.1 什么是灾难性回溯
某些正则模式在特定输入下会指数级增加匹配时间,导致程序卡死。这是正则最危险的陷阱。
典型危险模式:嵌套的量词 + 回溯。
import re # 危险模式:嵌套量词 pattern = re.compile(r"(a+)+b") # 输入:很多 a 但没有 b text = "a" * 30 # 这一行会跑很久(指数级时间)! # pattern.match(text)
原因:(a+)+ 在匹配失败时,会有指数级的拆分方式尝试。30 个 a,就有约 2^30 种拆分。
8.2 常见危险模式
| 危险模式 | 问题 |
|---|---|
(a+)+ | 嵌套量词 |
| `(a | a)*` |
(.*)* | 等价于嵌套量词 |
(a+){n,} | 量词套量词 |
(\w+\s?)* | 组合导致回溯 |
更隐蔽的例子:
# 看起来普通,但有灾难性回溯风险 pattern = re.compile(r"(\w+\s?)*$") text = "a" * 30 # pattern.match(text) # 会卡住
8.3 如何避免
方法 1:用更精确的模式
# ❌ 危险 r"(a+)+b" # ✅ 安全:不需要嵌套 r"a+b"
方法 2:非贪婪 + 锚点
# ❌ r"<(.+)>.*</\1>" # ✅ 非贪婪,但要配合正确锚点 r"<(.+?)>.*?</\1>"
方法 3:用原子分组 (?>...)(python 3.11+)
# 原子分组禁止回溯 # r"(?>a+)b"
方法 4:用非回溯的替代方案
# 简单场景:用字符串方法
if "b" in text and text.startswith("a"):
...
# 复杂场景:用多个简单正则组合方法 5:限制输入长度
if len(text) > 10000:
raise valueerror("输入太长")
m = pattern.match(text)8.4 检测和防御
- 用
re.debug查看编译后的正则结构:re.compile(r"...", re.debug) - 用测试工具:regex101.com 能可视化回溯过程
- 给正则加超时(python 标准库不支持,需第三方库
regex):
# pip install regex
import regex
try:
regex.match(r"(a+)+b", "a" * 30, timeout=1.0)
except timeouterror:
print("正则超时")8.5 安全的编写习惯
- 尽量用具体字符类,别用
.*漫天飞 - 优先用非贪婪
- 避免嵌套量词
- 长正则用
re.x拆开检查 - 限制输入大小
- 测试极端输入:空串、超长串、不匹配的长串
九、实战案例
9.1 邮箱验证与提取
import re
# 验证(简化版,覆盖 99% 场景)
email_pattern = re.compile(r"^[\w.+-]+@[a-za-z0-9-]+(\.[a-za-z0-9-]+)*\.[a-za-z]{2,}$")
def is_valid_email(email):
return bool(email_pattern.match(email))
for e in ["a@b.com", "user.name+tag@example.co.uk", "invalid@", "a@b"]:
print(e, is_valid_email(e))
# a@b.com true
# user.name+tag@example.co.uk true
# invalid@ false
# a@b false
# 从文本中提取
text = "联系 a@x.com 或 b.c@y.org;测试 invalid@"
emails = re.findall(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+", text)
print(emails) # ['a@x.com', 'b.c@y.org', 'invalid@']注意:
invalid@被提取出来了,因为正则允许不完整匹配。提取时通常要加边界。
9.2 手机号验证(中国)
import re
# 中国大陆手机号:1 开头,第二位 3-9,共 11 位
phone_pattern = re.compile(r"^1[3-9]\d{9}$")
phones = ["13812345678", "19987654321", "12345678901", "1234567890", "abc12345678"]
for p in phones:
print(p, bool(phone_pattern.match(p)))
# 13812345678 true
# 19987654321 true
# 12345678901 false(第二位 2)
# 1234567890 false(只有 10 位)
# abc12345678 false9.3 url 提取与解析
import re
text = """
访问 https://example.com/page?id=1 和 http://blog.site.org/post/123,
还有 www.example.net 和 ftp://files.example.com/data
"""
# 提取 url
url_pattern = r"(?:https?|ftp)://[^\s,。]+"
urls = re.findall(url_pattern, text)
print(urls)
# ['https://example.com/page?id=1', 'http://blog.site.org/post/123', 'ftp://files.example.com/data']
# 解析 url 组件
url = "https://www.example.com:8080/path/to/page?name=value&x=1#section"
pattern = re.compile(r"""
(?p<scheme>https?):// # 协议
(?p<host>[^/:]+) # 主机
(?::(?p<port>\d+))? # 端口(可选)
(?p<path>/[^?]*)? # 路径(可选)
(?:\?(?p<query>[^#]*))? # 查询串(可选)
(?:\#(?p<fragment>.*))? # 锚点(可选)
""", re.x)
m = pattern.match(url)
print(m.groupdict())
# {'scheme': 'https', 'host': 'www.example.com', 'port': '8080',
# 'path': '/path/to/page', 'query': 'name=value&x=1', 'fragment': 'section'}9.4 日期解析与格式转换
import re
# 支持多种日期格式
date_patterns = [
(re.compile(r"(\d{4})-(\d{2})-(\d{2})"), "{0}年{1}月{2}日"),
(re.compile(r"(\d{4})/(\d{2})/(\d{2})"), "{0}年{1}月{2}日"),
(re.compile(r"(\d{2})\.(\d{2})\.(\d{4})"), "{2}年{1}月{0}日"), # dd.mm.yyyy
]
def normalize_date(text):
for pattern, fmt in date_patterns:
m = pattern.search(text)
if m:
return fmt.format(*m.groups())
return none
for s in ["日期 2024-01-15", "日期 2024/01/15", "日期 15.01.2024"]:
print(normalize_date(s))
# 2024年01月15日
# 2024年01月15日
# 2024年01月15日9.5 日志解析
import re
log_pattern = re.compile(r"""
^(?p<time>\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})\s+ # 时间
\[(?p<level>\w+)\]\s+ # 级别
(?p<module>\w+):\s+ # 模块
(?p<message>.+)$ # 消息
""", re.x | re.m)
log_text = """2024-01-15 10:00:00 [info] server: 启动成功
2024-01-15 10:01:00 [warn] db: 连接慢,耗时 2s
2024-01-15 10:02:00 [error] api: 请求失败,状态码 500
2024-01-15 10:03:00 [info] server: 收到请求"""
for m in log_pattern.finditer(log_text):
info = m.groupdict()
print(f"{info['time']} | {info['level']:<5} | {info['module']:<6} | {info['message']}")
# 2024-01-15 10:00:00 | info | server | 启动成功
# 2024-01-15 10:01:00 | warn | db | 连接慢,耗时 2s
# 2024-01-15 10:02:00 | error | api | 请求失败,状态码 500
# 2024-01-15 10:03:00 | info | server | 收到请求9.6 文本清洗
import re
def clean_text(text):
# 1. 去掉 html 标签(简化版,真实场景用 beautifulsoup)
text = re.sub(r"<[^>]+>", "", text)
# 2. 多个空白合并成一个空格
text = re.sub(r"\s+", " ", text)
# 3. 去掉标点符号
text = re.sub(r"[^\w\s]", "", text)
# 4. 去掉连续重复的字符(如 "啊啊啊" → "啊")
# 注意:中文单字重复,慎用
text = re.sub(r"(.)\1{2,}", r"\1", text)
return text.strip()
dirty = "<p>hello world!!!</p> 这是 <b>python</b>"
print(clean_text(dirty)) # 'hello world 这是 python'9.7 提取结构化信息
import re
# 从自然语言中提取"姓名、年龄、城市"
text = """
张三,25 岁,来自北京;
李四,30 岁,来自上海;
王五,28 岁,来自广州。
"""
pattern = re.compile(r"(?p<name>[\u4e00-\u9fa5]{2,3})[,,]\s*(?p<age>\d+)\s*岁[,,]\s*来自(?p<city>[\u4e00-\u9fa5]+)")
for m in pattern.finditer(text):
print(m.groupdict())
# {'name': '张三', 'age': '25', 'city': '北京'}
# {'name': '李四', 'age': '30', 'city': '上海'}
# {'name': '王五', 'age': '28', 'city': '广州'}9.8 驼峰与下划线互转
import re
# 驼峰 → 下划线
def camel_to_snake(name):
# 在大写字母前插入下划线,再转小写
s1 = re.sub(r"(.)([a-z][a-z]+)", r"\1_\2", name)
return re.sub(r"([a-z0-9])([a-z])", r"\1_\2", s1).lower()
print(camel_to_snake("camelcase")) # 'camel_case'
print(camel_to_snake("httpserver")) # 'http_server'
print(camel_to_snake("myvariablename")) # 'my_variable_name'
# 下划线 → 驼峰
def snake_to_camel(name):
components = name.split("_")
return components[0] + "".join(x.title() for x in components[1:])
print(snake_to_camel("camel_case")) # 'camelcase'
print(snake_to_camel("http_server")) # 'httpserver'9.9 提取引号内容
import re
text = 'name = "张三", age = \'20\', city = "北京"'
# 提取所有双引号内容
print(re.findall(r'"(.*?)"', text)) # ['张三', '北京']
# 提取所有引号内容(单双引号都行)
print(re.findall(r'"([^"]*)"|\'([^\']*)\'', text))
# [('张三', ''), ('', '20'), ('北京', '')]
# 结果不干净,因为有两个分组
# 更优雅:命名分组 + 非捕获
pattern = re.compile(r"""(?:
"(?p<double>[^"]*)" |
'(?p<single>[^']*)'
)""", re.x)
for m in pattern.finditer(text):
content = m.group("double") or m.group("single")
print(content)
# 张三
# 20
# 北京9.10 验证密码强度
import re
def check_password(pwd):
errors = []
if len(pwd) < 8:
errors.append("至少 8 位")
if not re.search(r"[a-z]", pwd):
errors.append("需要小写字母")
if not re.search(r"[a-z]", pwd):
errors.append("需要大写字母")
if not re.search(r"\d", pwd):
errors.append("需要数字")
if not re.search(r"[!@#$%^&*(),.?\":{}|<>]", pwd):
errors.append("需要特殊字符")
return errors
for p in ["abc", "abc12345", "abc123!@#", "aaaaaaaaa1!"]:
errs = check_password(p)
status = "✓ 强密码" if not errs else "✗ " + "、".join(errs)
print(f"{p:<15} {status}")十、正则调试与学习工具
10.1 常用工具
| 工具 | 特点 |
|---|---|
| https://regex101.com | 首选,可视化、解释每一步、选 python 风格 |
| https://regexr.com | 更轻量,实时高亮 |
| https://pythex.org | 专门针对 python re |
re.debug | 打印编译后的结构 |
re.debug 示例:
import re
re.compile(r"(\d{4})-(\d{2})", re.debug)
输出:
subpattern 1
max_repeat 4 4
in
category category_digit
literal 45
subpattern 2
max_repeat 2 2
in
category category_digit10.2 调试步骤
正则匹配不符合预期时:
- 从最简单开始:先写
\d+,再加字符、量词、分组 - 逐步扩大:一次只改一个地方,看结果
- 用
re.findall验证:直接看匹配到了什么 - 关注边界:空串、超长串、特殊字符、换行
- 检查贪婪:看看是否需要
*? - 用可视化工具:regex101 能显示每一步回溯
10.3 学习路径
- 先掌握:
\d、\w、\s、.、*、+、?、{n,m}、[]、()、^、$、| - 再学:
findall、search、sub、分组、贪婪/非贪婪 - 进阶:命名分组、断言、
re.x、标志位 - 实战:把上面 9 节的案例都跑一遍,改成自己的需求
不要背正则。常用模式(邮箱、手机号、日期、url)抄下来作为模板,遇到新的用 regex101 边试边写。
十一、动手练习
练习 1:提取文本中所有 ipv4 地址(形如 192.168.1.1),并验证每段在 0-255 之间。
参考代码
import re
text = "服务器 192.168.1.1 和 10.0.0.255,无效 999.1.1.1 和 1.2.3"
# 基础提取
ips = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", text)
print(ips) # ['192.168.1.1', '10.0.0.255', '999.1.1.1']
# 严格版:每段 0-255
octet = r"(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)"
pattern = re.compile(rf"\b{octet}\.{octet}\.{octet}\.{octet}\b")
ips = pattern.findall(text)
print(ips) # ['192.168.1.1', '10.0.0.255']练习 2:写一个函数 extract_hashtags(text),提取文本中所有以 # 开头的标签,返回去重后的列表(保持顺序)。
参考代码
import re
def extract_hashtags(text):
tags = re.findall(r"#(\w+)", text)
# 保持顺序去重
seen = set()
result = []
for t in tags:
if t not in seen:
seen.add(t)
result.append(t)
return result
text = "学习 #python 和 #编程,再学 #python 和 #机器学习"
print(extract_hashtags(text))
# ['python', '编程', '机器学习']练习 3:把文本中所有英文单词首字母大写,其他字母小写(保留原有标点和空格)。
参考代码
import re
def title_words(text):
return re.sub(r"\b[a-za-z]+\b", lambda m: m.group().capitalize(), text)
print(title_words("hello world, this is python!"))
# 'hello world, this is python!'练习 4:用正则解析 key=value 格式的配置行(可能有多行、可能带注释 #),返回字典。
参考代码
import re
def parse_config(text):
config = {}
for line in text.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
m = re.match(r"^(\w+)\s*=\s*(.+)$", line)
if m:
key, value = m.groups()
config[key] = value.strip()
return config
text = """
# 配置
host = localhost
port=8080
debug = true
"""
print(parse_config(text))
# {'host': 'localhost', 'port': '8080', 'debug': 'true'}练习 5:写一个函数 mask_phone(text),把文本中所有手机号的中间 4 位替换成 ****。
参考代码
import re
def mask_phone(text):
return re.sub(r"\b(1[3-9]\d)\d{4}(\d{4})\b", r"\1****\2", text)
print(mask_phone("联系 13812345678 或 19987654321"))
# '联系 138****5678 或 199****4321'练习 6:提取一段文本中所有的中文姓名(简化规则:2-4 个连续汉字,出现在"姓名:"之后)。
参考代码
import re
text = "姓名:张三;姓名:李四光;备注:hello;姓名:欧阳娜娜"
# 断言前面是"姓名:"
names = re.findall(r"(?<=姓名:)[\u4e00-\u9fa5]{2,4}", text)
print(names)
# ['张三', '李四光', '欧阳娜娜']
# 或者用分组
names = re.findall(r"姓名:([\u4e00-\u9fa5]{2,4})", text)
print(names)
# 同上练习 7:验证一个字符串是不是合法的十六进制颜色值(#rgb 或 #rrggbb)。
参考代码
import re
pattern = re.compile(r"^#(?:[0-9a-fa-f]{3}|[0-9a-fa-f]{6})$")
for c in ["#fff", "#ff8800", "#abcd", "#12345", "fff", "#ggg"]:
print(c, bool(pattern.match(c)))
# #fff true
# #ff8800 true
# #abcd false
# #12345 false
# fff false
# #ggg false练习 8:把文本中的连续重复字符压缩成一个("aaaabbbcc" → "abc")。注意:要保留原来的中文标点和空格。
参考代码
import re
def compress(text):
return re.sub(r"(.)\1+", r"\1", text)
print(compress("aaabbbcccddd"))
# 'abcd'
print(compress("hello world")) # 空格也会被压缩
# 'helo world' ← l 也被压缩了!
# 只压缩重复的字母,不动标点和空白
def compress_letters(text):
return re.sub(r"([a-za-z])\1+", r"\1", text)
print(compress_letters("aaabbb hello world!!!"))
# 'ab helo world!!!'练习 9(陷阱题):找出下面这些正则可能存在的问题,并修复。
# 1. 匹配 html 中的 <script> 内容 r"<script>.*</script>" # 2. 匹配括号内容 r"\(.*\)" # 3. 提取所有引号字符串 r"['\"].*['\"]"
分析与修复
# 1. 问题:贪婪,且 . 不匹配换行 # 修复:非贪婪 + re.s r"<script>.*?</script>" # 配合 re.s # 2. 问题:贪婪,匹配了从第一个左括号到最后一个右括号 # 修复:非贪婪 r"\(.*?\)" # 3. 问题:贪婪;且没检查左右引号是否匹配 # 修复:非贪婪 + 后向引用 r"(['\"]).*?\1" # \1 保证左右引号一致
练习 10(综合):实现一个简单的 markdown 加粗和斜体转换:
**文本**→<strong>文本</strong>*文本*→<em>文本</em>
要求:不能误伤 url 中的 * 或 **,不能匹配没有闭合的标记。
参考代码
import re
def markdown_to_html(text):
# 先处理加粗(**),避免被斜体误匹配
text = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", text)
# 再处理斜体(*),要求 * 前后不是 *
text = re.sub(r"(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)", r"<em>\1</em>", text)
return text
samples = [
"这是 **加粗** 和 *斜体*",
"**两个** 和 *一个*",
"未闭合 **加粗",
"a * b * c",
]
for s in samples:
print(f"{s!r:<30} → {markdown_to_html(s)!r}")
# '这是 **加粗** 和 *斜体*' → '这是 <strong>加粗</strong> 和 <em>斜体</em>'
# '**两个** 和 *一个*' → '<strong>两个</strong> 和 <em>一个</em>'
# '未闭合 **加粗' → '未闭合 **加粗'
# 'a * b * c' → 'a <em> b </em> c' ← 这个例子会误伤真实场景中,markdown 解析需要更完整的词法分析,正则只能处理简单情况。这个练习是为了理解分组、断言、非贪婪的组合使用。
十二、本篇小结
基础语法:
- 字符类:
\d(数字)、\w(单词字符,含中文)、\s(空白),大写取反 - 字符集合:
[abc]、[a-z]、[^...] - 量词:
*(0+)、+(1+)、?(0/1)、{n}、{n,m} - 锚点:
^(开头)、$(结尾)、\b(单词边界) - 选择:
a|b - 转义:
\.、\*、\(;批量转义用re.escape()
re 模块函数:
| 函数 | 用途 |
|---|---|
match | 从开头匹配 |
search | 任意位置找第一个 |
findall | 找所有,返回列表 |
finditer | 找所有,返回 match 迭代器 |
sub | 替换 |
split | 拆分 |
fullmatch | 整个字符串必须完全匹配 |
compile | 预编译,反复使用 |
match 对象:
group()、group(n)、groups()、groupdict()start()、end()、span()- 命名分组:
(?p<name>...)
分组:
- 普通分组
(...):捕获内容 - 非捕获分组
(?:...):不捕获,只分组 - 命名分组
(?p<name>...):通过名字访问 - 后向引用
\1:引用前面分组的内容
贪婪 vs 非贪婪:
- 默认贪婪,
*?、+?、??、{n,m}?是非贪婪 - 不确定时优先用非贪婪
断言:
(?=...):后面必须是(?!...):后面不能是(?<=...):前面必须是(固定长度)(?<!...):前面不能是
标志位:
re.i:忽略大小写re.m:多行模式,^/$匹配行首尾re.s:.匹配换行re.x:详细模式,可分行加注释re.a:只匹配 ascii
性能陷阱:
- 避免嵌套量词
(a+)+ - 避免
(.*)* - 优先非贪婪
- 限制输入长度
- 复杂正则用
re.x拆开检查
最佳实践:
- 用原始字符串
r"..." - 复杂正则用
re.x分行加注释 - 反复使用的模式用
re.compile - 优先非贪婪
- 不要用正则解析 html/json/xml
- 用 regex101 调试
- 测试边界:空串、超长、特殊字符、换行
下一篇预告
扩展篇(四):并发编程——多线程、多进程、async/await
- 概念澄清:并发 vs 并行、cpu 密集 vs io 密集、gil 的真相
- 多线程:
threading模块、thread、lock、event、semaphore - 线程池:
concurrent.futures.threadpoolexecutor - 多进程:
multiprocessing、processpoolexecutor - 进程间通信:
queue、pipe、共享内存 - 异步 io:
asyncio、协程、async/await、asyncio.gather、task - asyncio 生态:
aiohttp、aiofiles、异步数据库 - 三种模型选型指南:什么时候用线程、进程、协程
- 综合实战:并发下载器、批量图片处理、异步爬虫
到此这篇关于python 正则表达式re模块全面讲解的文章就介绍到这了,更多相关python 正则表达式re模块内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论