使用函数作为repl参数实现动态替换
re.sub函数的第三个参数可以传入一个函数作为替换内容,该函数接收一个Match对象作为参数,通过它可以获取匹配的文本并生成动态替换内容。例如:
import re
def replacer(match):
return match.group(0).upper()
result = re.sub(r'[a-z]+', replacer, 'abc def')
print(result) # 输出:ABC DEF
使用函数作为repl参数实现动态替换
re.sub函数的第三个参数可以传入一个函数作为替换内容,该函数接收一个Match对象作为参数,通过它可以获取匹配的文本并生成动态替换内容。例如:
import re
def replacer(match):
return match.group(0).upper()
result = re.sub(r'[a-z]+', replacer, 'abc def')
print(result) # 输出:ABC DEF