python - 用大括号包裹数字的正则表达式?

标签 python regex backreference

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

相关文章:

java - 检查java中的模式和长度

python - Windows 上的 check_call 和命令行参数

python - 在 Keras 中加载权重后添加 DropOut

python + cx_freeze 'cannot get zipimporter instance'

正则表达式 可选组反向引用

regex - Spark DataFrame `regexp_replace` 中的反向引用

regex - Powershell替换中可能存在错误,还是我做错了?

Python Flask 请求 400 错误代码

c 正则表达式代码不起作用?

c++ - 正则表达式解析器生成器