首页 > 解决方案 > 正则表达式 python \1 \2 将字符串添加到结果文本的可能性

问题描述

我很想知道是否可以在 python 中的 re.search 操作的结果中添加一个字符串。

例如,我有字符串:

strExamp = "Julia the happy girl from the 6th century" 

我想要达到的结果是:

来自久违的 6 世纪的快乐女孩 Julia

我的代码:

pattern = r"([a-zA-Z ]*),([/d][a-zA-Z ]*)",r"\1, myText+ \2" --doesnt work ofc 
result = re.search(pattern, strExamp)

解决这个问题的方法是什么?

标签: pythonregex

解决方案


IIUC,用途:

import re

result = re.sub(r"(.*?)\s(\d+.*)", rf"\g<1> {my_text} \g<2>", strExamp)
print(result)

如果my_text = "long-gone"strExamp = "Julia the happy girl from the 6th century"这打印:

Julia the happy girl from the long-gone 6th century 

推荐阅读