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

发布于 2024-12-07 02:09:17 字数 812 浏览 0 评论 0原文

我正在尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

未蓝澄海的烟 2024-12-14 02:09:17
re.sub(r'e(\d+)', r'e{\1}', '12.34e56')

返回 '12.34e{56}'

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

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

returns '12.34e{56}'

or, the same result but different logic (don't replace e with e):

re.sub(r'(?<=e)(\d+)', r'{\1}', '12.34e56')
断肠人 2024-12-14 02:09:17

您的支架位置不正确。

这是一个解决方案,确保在 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}

Your brace placement is incorrect.

Here's a solution ensuring the that there's a number with optional decimal place before the 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)

Yields:

12.34e{56}
1e{10}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文