2

我正在尝试使用 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

谁能指出我的问题?谢谢您的帮助。

4

2 回答 2

7
re.sub(r'e(\d+)', r'e{\1}', '12.34e56')

返回'12.34e{56}'

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

re.sub(r'(?<=e)(\d+)', r'{\1}', '12.34e56')
于 2011-09-29T11:33:56.797 回答
1

您的支架位置不正确。

这是一个解决方案,确保在 之前有一个带有可选小数位的数字e

import re
samples = ['12.34e56','1e10']
for s in samples:
  print re.sub(r'(\d+(?:\.\d+)?)e([0-9]+)',"\g<1>e{\g<2>}",s)

产量:

12.34e{56}
1e{10}
于 2011-09-29T11:43:25.080 回答