首页 > 解决方案 > 正则表达式仅在花括号之间替换模式

问题描述

我试图用后面的字符替换 a':'或 a ,直到双花括号出现在双花括号之间时才出现空字符串。'|'}}''

例子:

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

应该变成:

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

我试过这个:

re.sub(r'(?<=\{\{\w*)[:\|](?=\}\})', '', s)

但它不起作用。我也得到一个错误: error: look-behind requires fixed-width pattern

标签: pythonregex

解决方案


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

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

推荐阅读