不是冗长手册,不是“背字典”——
这是一张能复制、能测试、能装逼的 Regex 彩虹表——
从\d到(?P<name>),从邮箱到 emoji,
1 张表 = 语法 + 实战 + Python 演示,全程可复制 📦
① 基础字符:一句话背完 ☕️
| 正则 | 一句话 | Python 演示 |
|---|---|---|
\d | 任意数字 | re.findall(r"\d", "a1b2") → ['1', '2'] |
\D | 非数字 | re.findall(r"\D", "a1b2") → ['a', 'b'] |
\w | 字母数字下划线 | re.findall(r"\w+", "hi_99") → ['hi_99'] |
\W | 非单词 | re.findall(r"\W+", "hi!!") → ['!!'] |
\s | 空白 | re.findall(r"\s+", "a\tb\n") → ['\t', '\n'] |
\S | 非空白 | re.findall(r"\S+", "a b") → ['a', 'b'] |
口诀:**“小写肯定,大写否定,加号贪婪,星号懒惰”**🎵
② 边界定位:一句话秒懂 🧭
| 正则 | 一句话 | Python 演示 |
|---|---|---|
^ | 开头 | re.findall(r"^\d+", "123abc") → ['123'] |
$ | 结尾 | re.findall(r"\d+$", "abc123") → ['123'] |
\b | 单词边界 | re.findall(r"\b\w+\b", "hi!") → ['hi'] |
\B | 非边界 | re.findall(r"\B\w+\B", "hi!") → [] |
口诀:“开头 ^,结尾 $,边界 \b,定位不迷路”
③ 量词:贪婪 vs 懒惰 ⚡️
| 正则 | 贪婪 | 懒惰 | Python 对比 |
|---|---|---|---|
* | 0 或更多 | *? | re.findall(r"a*", "aaa") → ['aaa'] vs *? → ['a', 'a', 'a'] |
+ | 1 或更多 | +? | re.findall(r"a+", "aaa") → ['aaa'] vs +? → ['a', 'a', 'a'] |
? | 0 或 1 | ?? | re.findall(r"a?", "aaa") → ['a', 'a', 'a'] vs ?? → ['', '', ''] |
{n,m} | n 到 m | {n,m}? | re.findall(r"a{2,3}", "aaa") → ['aaa'] vs {2,3}? → ['aa'] |
口诀:“默认贪婪,加 ? 懒惰,{n,m} 精确”
④ 分组与命名:捕获 + 命名 🏷️
| 正则 | 一句话 | Python 演示 |
|---|---|---|
() | 捕获分组 | re.search(r"(\d+)", "a123b").group(1) → '123' |
(?:) | 非捕获 | re.search(r"(?:\d+)", "a123b").group(0) → '123' |
(?P<name>) | 命名分组 | re.search(r"(?P<num>\d+)", "a123b").group('num') → '123' |
口诀:“() 捕获,(?:) 不捕获,(?P) 起名字”
⑤ 实战 1:邮箱提取(一行)📧
import re
text = "Contact me at alice@example.com or bob+tag@sub.co.uk"
emails = re.findall(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", text)
print(emails) # ['alice@example.com', 'bob+tag@sub.co.uk']
⑥ 实战 2:手机号格式化(一行)📱
import re
phone = "13812345678"
formatted = re.sub(r"(\d{3})(\d{4})(\d{3})", r"\1-\2-\3", phone)
print(formatted) # 138-1234-5678
⑦ 实战 3:Emoji 提取(一行)😀
import re
text = "I ❤️ Python 🐍 and 🎄"
emojis = re.findall(r"[\u2639-\u3299]", text)
print(emojis) # ['❤️', '🐍', '🎄']
⑧ 万能解毒剂:调试 checklist✅
| 问题 | 解毒 |
|---|---|
| 贪婪过头 | 加 ? 变懒惰 |
| 分组混乱 | 用 (?P<name>) 命名 |
| 特殊字符 | 用 re.escape(text) |
| 性能慢 | 预编译 re.compile(pattern) |
⑨ 彩蛋:彩虹正则调试器(10 行)
import re, random, math
def rainbow_regex(pattern, text):
for m in re.finditer(pattern, text):
hue = m.start() / len(text)
r = int(255 * (1 + math.cos(hue * 6.28)) / 2)
g = int(255 * (1 + math.cos(hue * 6.28 + 2)) / 2)
b = int(255 * (1 + math.cos(hue * 6.28 + 4)) / 2)
print(f"\033[38;2;{r};{g};{b}m{m.group()}\033[0m", end="")
print()
# 使用
rainbow_regex(r"\d+", "a123b456c789")
🏁 一句话口诀(背它!)
**“小写肯定,大写否定,^$定位,()捕获,?懒惰,{n,m}精确,彩虹调试深拷贝!”**🎵