如何在另一个字符串上应用正则表达式组匹配?

How to apply regex group matching on another string?

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

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

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

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

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

为什么不完全避免使用正则表达式并执行如下操作:

inputString = "testImage123.jpg"
filename, _, ext = inputString.rpartition(".")

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