我正在尝试使用 Pythonre.sub()
将字符串与e
字符匹配,并在字符之后和最后一个数字之后立即插入花括号e
。例如:
12.34e56 to 12.34e{56}
1e10 to 1e{10}
我似乎找不到正确的正则表达式来插入所需的花括号。例如,我可以像这样正确插入左大括号:
>>> 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
使用两个反向引用时出现了我的问题。
>>> 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
谁能指出我的问题?谢谢您的帮助。