Python 正则表达式仅在花括号之间替换模式

Python 正则表达式仅在花括号之间替换模式,python,regex,Python,Regex,我试图用后面的字符替换':'或'|',直到双}为空字符串',仅当它出现在双大括号之间时 例如: s=“这是我想要的{{example_string:default_或{unne}}或{{some_variable{124; yeah}}}的字符串,应该是:未触及的” 应成为: “这是我想要的{{example_string}或{{some_variable}}},应该:未触及” 我试过这个: re.sub(r'(?以下是如何使用re.sub(): 输出: This is an {{example

我试图用后面的字符替换
':'
'|'
,直到双
}
为空字符串
'
,仅当它出现在双大括号之间时

例如:

s=“这是我想要的{{example_string:default_或{unne}}或{{some_variable{124; yeah}}}的字符串,应该是:未触及的”

应成为:

“这是我想要的{{example_string}或{{some_variable}}},应该:未触及”

我试过这个:


re.sub(r'(?以下是如何使用
re.sub()

输出:

This is an {{example_string}} or {{some_variable}} of what I want and this should:be untouched

在我的手机上打字,但为什么不简单地

import re

s = "This is an {{example_string:default_or_none}} or {{some_variable|yeah}} of what I want and this should:be untouched"

p = re.compile(r"\{\{(\w+)[\|\:]\w+\}\}")

print(p.sub(r"{{\1}}", s))

即使在花括号内有多个
|
的情况下,以下操作也适用:

import re

s = "This is an {{example_string:default_or_none|other|filter:whatever}} or {{some_variable|yeah}} of what I want and this should:be untouched"
result = re.sub('\{\{(\w+).*?\}\}', r'{{\1}}', s)
print(result)
输出

This is an {{example_string}} or {{some_variable}} of what I want and this should:be untouched

错误是告诉你不能在
中使用
\w*
(?如果我有多个管道,比如:
{this}for | example |和| this}}
来制作这个
{this}
我如何摆脱上面的模式,但是使用多个管道和冒号,比如
{this}{for{example}和{this}/code>{“用同样的逻辑?”贾斯汀·埃泽奎尔(justin_ezequiel)
This is an {{example_string}} or {{some_variable}} of what I want and this should:be untouched