使用`re.sub()`函数时,如何通过回调函数动态替换匹配的文本?请给出代码示例。
import re
# 示例1:通过回调函数将匹配的数字加倍
def double_match(match):
"""
将匹配的数字乘以2
"""
num = int(match.group(0))
return str(num * 2)
text = "今天的温度是25度,明天的温度是30度。"
# 匹配所有数字并通过回调函数替换
result = re.sub(r'\d+', double_match, text)
print(result) # 输出:今天的温度是50度,明天的温度是60度。
# 示例2:通过回调函数动态替换大小写
case_switch = {'apple': '苹果', 'banana': '香蕉'}
def translate_match(match):
"""
根据匹配的单词动态替换为对应的中文
"""
word = match.group(0)
return case_switch.get(word.lower(), word)
text = "I have an Apple and a Banana."
# 匹配单词并通过回调函数替换
result = re.sub(r'\b\w+\b', translate_match, text, flags=re.IGNORECASE)
print(result) # 输出:I have an 苹果 and a 香蕉.
# 示例3:通过回调函数实现复杂的替换逻辑
def format_phone(match):
"""
将电话号码格式化为标准格式
"""
phone = match.group(0)
# 假设电话号码格式为:123-456-7890
return f"({phone[:3]}) {phone[4:7]}-{phone[8:]}"
text = "请拨打电话123-456-7890联系我们。"
# 匹配电话号码并通过回调函数替换
result = re.sub(r'\d{3}-\d{3}-\d{4}', format_phone, text)
print(result) # 输出:请拨打电话(123) 456-7890联系我们。
# 示例4:通过回调函数实现条件替换
def replace_conditional(match):
"""
根据匹配的内容动态决定替换结果
"""
word = match.group(0)
if len(word) > 5:
return "LONG"
else:
return "SHORT"
text = "Python is a powerful programming language."
# 匹配单词并根据长度替换
result = re.sub(r'\b\w+\b', replace_conditional, text)
print(result) # 输出:SHORT SHORT a SHORT SHORT SHORT.
# 示例5:通过回调函数实现分组替换
def swap_groups(match):
"""
交换匹配分组的位置
"""
first = match.group(1)
second = match.group(2)
return f"{second} {first}"
text = "John Doe, Jane Smith"
# 匹配姓名并交换分组
result = re.sub(r'(\w+) (\w+)', swap_groups, text)
print(result) # 输出:Doe John, Smith Jane
详细说明
re.sub()函数是Python中用于正则表达式替换的核心方法之一。它的基本语法是:
re.sub(pattern, repl, string, count=0, flags=0)
当repl参数为一个函数时,re.sub()会将每个匹配到的内容传递给该函数,并将函数的返回值作为替换结果。这种机制非常适合需要动态生成替换内容的场景。
关键点
- 回调函数的参数:回调函数接收一个匹配对象(
re.Match),可以通过group()方法获取匹配的内容或分组。 - 返回值:回调函数必须返回一个字符串,作为最终的替换内容。
- 性能:对于需要频繁替换的场景,使用回调函数比静态替换更灵活,但可能会稍微降低性能。
- 分组支持:如果正则表达式中包含分组,回调函数可以通过
group(1),group(2)等方式访问。
适用场景
- 动态格式化文本(如日期、电话号码)。
- 条件替换(根据匹配内容决定替换结果)。
- 多语言翻译或映射替换。
- 复杂逻辑的文本处理。