import re
# 原始字符串
text = "The price is $10.99 for item ABC123 and $20.45 for item DEF456."
# 正则表达式模式,其中(\d+\.\d+)是将被替换的变化部分
pattern = r'The price is $(\d+\.\d+)'
# 替换函数,保留"The price",并将其替换为"PRICE_PLACEHOLDER"
def replace_price(match):
return "The price is PRICE_PLACEHOLDER"
# 使用re.sub和替换函数
new_text = re.sub(pattern, replace_price, text)
print(new_text)
#输出:The price is PRICE_PLACEHOLDER for item ABC123 and $20.45 for item DEF456.
如果想要在替换中引用分组的内容,可以在替换函数中使用match.group(n)
,其中n
是分组的索引(从1开始)。例如,保留原始价格并在其前后添加一些文本:
def replace_price(match):
# 获取第一个分组(即价格)
price = match.group(1)
return f"The price is NEW_PRICE_{price}_PLACEHOLDER"
new_text = re.sub(pattern, replace_price, text)
print(new_text)
#输出:The price is NEW_PRICE_10.99_PLACEHOLDER for item ABC123 and $20.45 for item DEF456.