Skip to content

14 正则表达式

📋 资料说明

  • 来源:课程 day13 前半(视频 00~02)
  • 笔记尚硅谷大模型技术之Python1.0.docx 第 15 章
  • 代码:无独立代码文件
  • 视频:❌ 跳过(共 3 个视频:正则介绍 → 常用匹配字符 → 案例)

🟢 🤖 AI 替代率:95%

为什么是这个水平:

正则语法是确定性模式匹配规则,AI 可以精确生成复杂的正则表达式。在 AI 时代,正则表达式的价值已经大幅下降——大多数人不需要记忆正则语法,直接让 AI 写正则比自己在文档中查找快 10 倍。

唯一需要人类的是:在特殊情况下(中文匹配、Unicode 处理)可能要调整 AI 生成的表达式。


👤 人工干预率:5%

建议:不记语法,学会"让 AI 写正则"即可。只需知道 re 模块的四个主要函数:searchmatchfindallsub


1. 常用匹配字符

模式匹配示例
.任意单个字符(除换行)a.b 匹配 "acb"
\d数字 [0-9]\d{3} 匹配 "123"
\w单词字符 [a-zA-Z0-9_]\w+ 匹配 "hello"
\s空白字符空格、制表符、换行
^开头^hello 匹配 "hello" 开头
$结尾world$ 匹配以 "world" 结尾
*0 次或多次ab*c 匹配 "ac"、"abc"、"abbc"
+1 次或多次ab+c 匹配 "abc"、"abbc",不匹配 "ac"
?0 次或 1 次ab?c 匹配 "ac"、"abc"
{n}精确 n 次\d{3} 匹配 3 位数字
{n,}至少 n 次\d{3,} 匹配 3 位以上数字
{n,m}n 到 m 次\d{2,4} 匹配 2~4 位数字
[abc]字符集[aeiou] 匹配任意元音字母
[^abc]排除字符集[^0-9] 匹配非数字字符
\b单词边界\bword\b 匹配完整的 "word"
``

2. re 模块核心函数

python
import re

text = "我的电话是 138-1234-5678,邮箱是 alice@email.com"

# search:查找第一个匹配
phone = re.search(r"\d{3}-\d{4}-\d{4}", text)
if phone:
    print(phone.group())  # 138-1234-5678

# findall:查找所有匹配
emails = re.findall(r"\w+@\w+\.\w+", text)
print(emails)  # ['alice@email.com']

# match:从字符串开头匹配(match 不是"匹配整个字符串"!)
# 等价于 search 加 ^
result = re.match(r"\d", text)
print(result)  # None(开头是"我",不是数字)

# sub:替换
censored = re.sub(r"\d", "*", text)
print(censored)  # 我的电话是 ***-****-****,邮箱是 alice@email.com

# split:分割
parts = re.split(r"[,。!?\s]", text)
print(parts)  # ['我的电话是', '138-1234-5678', '邮箱是', 'alice@email.com']

3. 常用正则案例

python
import re

# 手机号码
phone = "13812345678"
print(re.match(r"1[3-9]\d{9}$", phone))  # 匹配 11 位手机号

# 邮箱
email = "user.name@company.com.cn"
pattern = r"^[\w.]+@[\w.]+\.\w+$"
print(re.match(pattern, email))

# URL
url = "https://www.example.com/path?q=python"
pattern = r"https?://[\w./?=&-]+"
print(re.match(pattern, url))

# IP 地址
ip = "192.168.1.1"
pattern = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
print(re.match(pattern, ip))

# 中文字符
chinese_text = "Hello 世界"
chinese = re.findall(r"[\u4e00-\u9fff]+", chinese_text)
print(chinese)  # ['世界']

练习题

练习 1:提取数字

从字符串 "单价 25 元,数量 3,总价 75 元" 中提取所有数字。

练习 2:邮箱验证

判断 "test@example.com" 是否是合法邮箱格式。

练习 3:替换敏感信息

"我的身份证是 110101199001011234" 中的身份证号替换为 ************


参考答案

练习 1:

python
import re
text = "单价 25 元,数量 3,总价 75 元"
numbers = re.findall(r"\d+", text)
print(numbers)  # ['25', '3', '75']

练习 2:

python
import re
email = "test@example.com"
pattern = r"^[\w.]+@[\w.]+\.\w+$"
print(bool(re.match(pattern, email)))  # True

练习 3:

python
import re
text = "我的身份证是 110101199001011234"
censored = re.sub(r"\d{18}", "************", text)
print(censored)  # 我的身份证是 ************

OPC 超级个体实战指南