Python re 模块

Python re.sub() 函数用于替换所有匹配的内容。

语法

re.sub(pattern, repl, string, count=0)

参数

pattern:正则。第二个参数 repl:替换内容(可含 \1 引用分组,或是函数)。第三个参数 string:原字符串。可选 count:替换次数。

返回值

返回替换后的新字符串。

示例

import re

print(re.sub(r"\d+", "#", "a1b2c3"))       # a#b#c
print(re.sub(r"\d+", "#", "a1b2c3", count=2))  # a#b#c3,只替换2次

# 用引用的分组替换
print(re.sub(r"(\w+)@(\w+)", r"\2@\1", "a@b"))  # b@a,交换

# 清理空白
print(re.sub(r"\s+", " ", "hello   world  ok"))  # hello world ok

# 替换成函数
def hide_digits(m):
    return "*" * len(m.group())
print(re.sub(r"\d+", hide_digits, "手机 13812345678"))  # 手机 ***********

注意事项

count 限制替换次数。repl 里 \1 引用分组。r 前缀(原始字符串)避免转义问题。