python-3.x - 如何在另一个字符串上应用正则表达式组匹配?
问题描述
使用 Python 3,我试图将模式组从从字符串恢复的正则表达式替换为另一个字符串,例如:
使用以下正则表达式“([az]+).([az]{3})”和以下字符串:“image.jpg”,我想将组替换为另一个字符串,即“您的文件\2 类型的名称为 \1."。
这将导致字符串为“您的 jpg 类型的文件具有名称图像”。
使用, 并通过做re.search
循环,但如果组有超过 9 个条目,它会中断。我希望有一种更有效的方法来做到这一点。.groups()
destination.replace('\{pos}', current)
据我所知,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."
推荐阅读
- amazon-web-services - 我们可以在 CloudWatch 中为 Sagemaker 笔记本实例生成自定义日志吗?
- activemq-artemis - ActiveMQ Artemis 中的分页模式
- docker-compose - 使用 Docker Compose 设置 Prometheus
- reactjs - Material-UI:如何在 TextField 标签中添加图标?
- coordinates - 定向问题笛卡尔坐标到俯仰滚动偏航
- c# - 我将如何检查 e.item 是否与 collectionviewsource 中的对象相同?
- c# - 使用 C#/.NET 从白色背景图像(A4 纸)中提取对象(签名)?
- python - 使用“del”删除列表项不起作用
- azure-active-directory - 使用 Azure AD 登录 Web 应用程序时出现可怕的 AADSTS50011 回复 url 错误 - 在 localhost 上运行良好
- r - 添加 R 包作者而不联系他们