跳转到主要内容
模块 8 · 第 4 课(共 4)课程中的32/36~12 min
模块课程(4/4)

re 模块:Python 中的正则表达式

re 模块公开了 Python 中的正则表达式。如果你已经采取了 本网站上的正则表达式课程,您会发现所有语法都很熟悉;这里 我们看看 API。

原始字符串:r"..."

正则表达式使用许多反斜杠(\d、\b、\s)。始终将它们写为 原始字符串,因此您不必将它们加倍:

Python
import re
# raw: \d is a single token
pattern = r"\d+"
# NOT raw: you would have to write "\\d+" otherwise Python interprets \d as "d"

re.search:查找第一个出现的位置

Python
import re
m = re.search(r"\d+", "ho 42 mele e 17 pere")
m.group()    # '42'
m.start()    # 3
m.end()      # 5

如果找到,则返回 Match 对象,否则返回 None 。惯用模式:

Python
if m := re.search(r"\d+", testo):
    print(m.group())

re.match:仅在字符串的开头

Python
re.match(r"\d+", "42 anni")     # match!
re.match(r"\d+", "ho 42 anni")  # None (doesn't start with a digit)

要在任何地方搜索,首选re.search。

re.findall:所有出现的情况

Python
re.findall(r"\d+", "ho 42 mele, 17 pere, 3 banane")
# ['42', '17', '3']

如果模式具有 捕获组,则 findall 返回组,而不是 整场比赛:

Python
re.findall(r"(\w+)@(\w+)", "ada@x bob@y")
# [('ada', 'x'), ('bob', 'y')]

re.sub:替换

Python
re.sub(r"\d+", "###", "ho 42 mele e 17 pere")
# 'ho ### mele e ### pere'

它还可以与替换函数(接收匹配)一起使用:

Python
re.sub(r"\d+", lambda m: str(int(m.group()) * 2), "ho 42 mele")
# 'ho 84 mele'

命名组

Python
m = re.search(r"(?P<anno>\d{4})-(?P<mese>\d{2})-(?P<giorno>\d{2})", "2025-01-15")
m.group("anno")    # '2025'
m.groupdict()      # {'anno': '2025', 'mese': '01', 'giorno': '15'}

有用的标志

Python
re.search(r"ciao", "CIAO", re.IGNORECASE)       # case-insensitive
re.findall(r"^.+$", testo, re.MULTILINE)        # ^/$ match every line
re.search(r"a.b", "a\nb", re.DOTALL)            # . matches newline too

re.finder 用于内存安全

如果需要处理巨大文本块中的匹配项,re.findall 会在内存中分配一个列表,其中包含所有提取的匹配字符串。最好使用 re.finditer(),它会生成 Match 对象的惰性迭代器,消耗最少的内存。

尝试一下

锻炼#python.m8.l4.e1
尝试:0加载中...

给定 `text = 'ordine #123, totale €45.50, Ricevuta #456'`,将所有订单号(# 后面的数字)提取到 `orders` 作为字符串列表。评估“订单”。

正在加载编辑器...
显示提示

re.findall(r"#(\\d+)", text) — 仅捕获数字组。

3 次尝试后可用的解决方案

复习练习

锻炼#python.m8.l4.e2
尝试:0加载中...

给定 `s = 'tel: 06-12345678 e tel: 02-9876'`,将所有电话号码(格式 \\d+-\\d+)替换为字符串 'XXX' 并分配给 `masked`。评估“蒙面”。

正在加载编辑器...
显示提示

re.sub(r"\\d+-\\d+", "XXX", s)

3 次尝试后可用的解决方案

额外的挑战

锻炼#python.m8.l4.e3
尝试:0加载中...

导入 \`re\` 模块。从字符串 \`log_line = "Error 404 in 15ms"\` 中提取由一位或多位数字组成的所有数字。将列表存储在“numbers”中并对其进行评估。

正在加载编辑器...
显示提示

使用 re.findall(r'\\d+', log_line) 将所有数字提取为字符串列表。

3 次尝试后可用的解决方案