首页 > 解决方案 > 用大括号自动替换圆括号

问题描述

我有以下文字:

text = "The equation is Ue^(jα)."

当第一个圆括号前面有 a 时,我想(用括号自动替换括号。{^

所以我尝试了:

text = "The equation is Ue^(jα). Some brackets like those () should stay. If this symbol ^ is alone nothing should happen. "
text = re.sub(r'^((.*?))<',r'^{\1} ', text)
text

...但它似乎不起作用。知道我怎样才能让它工作吗?

像这样的一些括号()应该保留。如果仅此符号^,则不应发生任何事情。

标签: pythonregex

解决方案


您忘记转义一些字符:

>>> text = "The equation is Ue^(jα). Some brackets like those () should stay. If this symbol ^ is alone nothing should happen. "
>>> re.sub(r'\^\((.*?)\)',r'^{\1} ', text)
'The equation is Ue^{jα} . Some brackets like those () should stay. If this symbol ^ is alone nothing should happen. '

推荐阅读