用圆括号自动替换圆括号

时间:2019-05-02 20:06:07

标签: python regex

我有以下文字:

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

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

所以我尝试了:

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

...但是它似乎不起作用。知道如何使它起作用吗?

应该保留诸如()之类的括号。如果单独使用此符号^,则什么也不会发生。

1 个答案:

答案 0 :(得分:1)

您忘了逃脱一些字符:

>>> 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. '