用大括号包裹数字的正则表达式?

drb*_*sen 2 python regex backreference

我正在尝试使用Python re.sub()将字符串与e字符匹配,并在e字符后面和lastdigit后立即插入花括号.例如:

12.34e56 to 12.34e{56}
1e10 to 1e{10}
Run Code Online (Sandbox Code Playgroud)

我似乎无法找到正确的正则表达式插入所需的花括号.例如,我可以像这样正确插入左括号:

>>> import re
>>> x = '12.34e10'
>>> pattern = re.compile(r'(e)')
>>> sub = z = re.sub(pattern, "\1e{", x)
>>> print(sub)
    12.34e{10 # this is the correct placement for the left brace
Run Code Online (Sandbox Code Playgroud)

使用两个反向引用时出现问题.

>>> import re
>>> x = '12.34e10'
>>> pattern = re.compile(r'(e).+($)')
>>> sub = z = re.sub(pattern, "\1e{\2}", x)
>>> print(sub)
    12.34e{} # this is not what I want, digits 10 have been removed
Run Code Online (Sandbox Code Playgroud)

任何人都可以指出我的问题吗?谢谢您的帮助.

eum*_*iro 7

re.sub(r'e(\d+)', r'e{\1}', '12.34e56')
Run Code Online (Sandbox Code Playgroud)

回报 '12.34e{56}'

或者,相同的结果,但不同的逻辑(不替换ee):

re.sub(r'(?<=e)(\d+)', r'{\1}', '12.34e56')
Run Code Online (Sandbox Code Playgroud)