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



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

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

这将导致字符串为"您的文件类型为jpg,名称为image.">

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

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

#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."

为什么不完全避免使用正则表达式呢?

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.

最新更新