用大括号包裹数字的正则表达式?
我正在尝试使用 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
谁能指出我的问题吗?感谢您的帮助。
I am trying to using Python's re.sub()
to match a string with an e
character and insert curly braces immediately after the e
character and after the lastdigit. For example:
12.34e56 to 12.34e{56}
1e10 to 1e{10}
I can't seem to find the correct regex to insert the desired curly braces. For example, I can properly insert the left brace like this:
>>> 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
My problem arises when using two back references.
>>> 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
Can anyone point out my problem? Thanks for the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
返回
'12.34e{56}'
或者,相同的结果但不同的逻辑(不要将
e
替换为e
):returns
'12.34e{56}'
or, the same result but different logic (don't replace
e
withe
):您的支架位置不正确。
这是一个解决方案,确保在
e
之前有一个带有可选小数位的数字:产量:
Your brace placement is incorrect.
Here's a solution ensuring the that there's a number with optional decimal place before the
e
:Yields: