【发布时间】:2011-09-29 11:29:26
【问题描述】:
我正在尝试使用 Python 的 re.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
谁能指出我的问题?感谢您的帮助。
【问题讨论】:
标签: python regex backreference