我正在尝试使用 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
谁能指出我的问题?感谢您的帮助。
最佳答案
re.sub(r'e(\d+)', r'e{\1}', '12.34e56')
返回 '12.34e{56}'
或者,结果相同但逻辑不同(不要将e
替换为e
):
re.sub(r'(?<=e)(\d+)', r'{\1}', '12.34e56')
关于python - 用大括号包裹数字的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7596667/