0Pricing
Python Academy · 课时

re.sub、标志与编译模式

替换文本,使用 IGNORECASE 等标志,并编译模式以便重复使用。

re.sub、标志与编译模式 是 CoddyKit 上的免费 Python Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Python Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Python Academy 课程共包含 4 节课。

简介

re.sub 会替换匹配项。标志会修改匹配行为。对于重复使用,已编译的模式效率更高。

re.sub 基础

re.sub(pattern, repl, string) 会将所有匹配项替换为 repl。第 4 个参数 count= 会限制替换次数。
import re
result = re.sub(r'\d+', 'X', 'abc 123 def 456')
print(result)

使用组进行 re.sub

请在替换内容中使用 \1、\2 或 \g<1> 来插入捕获组。命名组使用 \g。
import re
# Swap first and last name
result = re.sub(r'(\w+),\s*(\w+)', r'\2 \1', 'Smith, John')
print(result)

使用函数进行 re.sub

替换内容可以是可调用对象:f(match) → 替换字符串。这样可以实现复杂的转换。
import re
def double_num(m): return str(int(m.group())*2)
result = re.sub(r'\d+', double_num, '1 cats and 2 dogs')
print(result)

re.IGNORECASE (re.I)

使模式不区分大小写。带有 re.I 的 r'hello' 可以匹配 'HELLO'、'Hello' 等内容。
import re
print(re.findall(r'hello', 'Hello HELLO hello', re.I))

re.MULTILINE (re.M)

使 ^ 和 $ 匹配每一行的开头和结尾,而不是整个字符串的开头和结尾。
import re
text = 'first\nsecond\nthird'
print(re.findall(r'^\w+', text, re.M))

re.DOTALL (re.S)

使 . 也能匹配换行符。没有此标志时,. 会在行边界处停止。
import re
text = 'line1\nline2'
print(re.search(r'line1.line2', text, re.S).group())

re.VERBOSE (re.X)

允许在模式中加入注释和空白,以提高可读性。空格会被忽略;如需匹配字面空格,请使用 \ 加空格。
import re
pattern = re.compile(r'''
    (?P<year>\d{4})   # year
    -
    (?P<month>\d{2}) # month
    -
    (?P<day>\d{2})   # day
''', re.X)
print(pattern.search('2024-01-15').groupdict())

组合标志

请使用 | 组合标志:re.I | re.M。也可以在模式开头使用内联标志 (?im)。
import re
print(re.findall(r'^\w+', 'Hello\nWorld', re.I | re.M))

使用 re.compile 提升性能

使用 re.compile() 将模式编译一次。在已编译的对象上调用方法:pat.search()、pat.findall()。
import re
email_re = re.compile(r'[\w.+-]+@[\w-]+\.[\w.]+')
emails = ['user@example.com', 'invalid', 'test@test.org']
print([e for e in emails if email_re.fullmatch(e)])

re.escape()

re.escape(string) 会转义字符串中的所有特殊正则表达式字符,因此该字符串可以用作字面模式。
import re
user_input = 'price.is $10+'
pattern = re.compile(re.escape(user_input))
text = 'The price.is $10+ today'
print(bool(pattern.search(text)))

快速检查

在 Python 正则表达式中,哪个标志会使 . 匹配换行符?

总结

re.sub:使用字符串、组或函数进行替换。标志:re.I(大小写)、re.M(多行 ^/$)、re.S(点号匹配 \n)、re.X(详细模式)。编译模式以便复用。

继续学习

做得很好!下一课正在等待您。

常见问题解答

「re.sub、标志与编译模式」课时是免费的吗?

是的 — 「re.sub、标志与编译模式」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Python Academy 课程的其余内容,请升级到 CoddyKit PRO。 Python Academy 课程共包含 4 节课。

「re.sub、标志与编译模式」这节课中我会学到什么?

替换文本,使用 IGNORECASE 等标志,并编译模式以便重复使用。 你通过在浏览器中直接运行的动手代码来练习 Python Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Python Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Python Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「re.sub、标志与编译模式」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Python Academy 课中编写并运行代码吗?

能。每节 Python Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 正则表达式基础
  2. 使用 re.match、re.search、re.findall
  3. 分组与命名捕获
  4. re.sub、标志与编译模式
← 返回 Python Academy