将数字用花括号括起来的正则表达式?
我正在尝试使用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
有没有人能指出我的问题所在?谢谢大家的帮助。
2 个回答
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}
7
re.sub(r'e(\d+)', r'e{\1}', '12.34e56')
返回 '12.34e{56}'
或者,结果一样但逻辑不同(不要把 e
替换成 e
):
re.sub(r'(?<=e)(\d+)', r'{\1}', '12.34e56')