首页 > 解决方案 > 如何在另一个字符串上应用正则表达式组匹配?

问题描述

使用 Python 3,我试图将模式组从从字符串恢复的正则表达式替换为另一个字符串,例如:

使用以下正则表达式“([az]+).([az]{3})”和以下字符串:“image.jpg”,我想将组替换为另一个字符串,即“您的文件\2 类型的名称为 \1."。

这将导致字符串为“您的 jpg 类型的文件具有名称图像”。

使用, 并通过做re.search循环,但如果组有超过 9 个条目,它会中断。我希望有一种更有效的方法来做到这一点。.groups()destination.replace('\{pos}', current)

据我所知,re.sub适用于同一个字符串,这就是为什么我不能使用它。

标签: python-3.xregexre

解决方案


#python3
import re
exp=r"([a-z]+).([a-z]{3})"
stri="image.jpg"
f= r"Your file of type \2 has the name \1."
result= re.sub(exp, f, stir)
print(result)
#output: "Your file of type jpg has the name image."

推荐阅读