🎯 正则表达式「彩虹速查表」:一句话 + 一行代码 + 一个彩蛋!

45 阅读1分钟

不是冗长手册,不是“背字典”——
这是一张能复制、能测试、能装逼的 Regex 彩虹表——
\d(?P<name>),从邮箱到 emoji,
1 张表 = 语法 + 实战 + Python 演示,全程可复制 📦

微信图片_20251014151033_10_20.jpg

① 基础字符:一句话背完 ☕️

正则一句话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}精确,彩虹调试深拷贝!”**🎵