给定一个逗号分隔的数字"123,456,789"作为字符串,我尝试构建一个正则表达式模式,该模式匹配(包括)最左边的逗号','到最后一个整数(单位位数)数字'9'。对于上述字符串中的数字,应匹配",456,789"。
我的代码如下:
import re
print(re.findall(r"(,\d{3})*", "123,456,789"))
# The above regular expression pattern is actually part of a much larger
# regular expression pattern to match a number that may or may not be
# comma delimited or be in scientific notation. The pattern is:
# r"([-+]?\d+){1}(,\d{3})*(\.\d+)?([Ee][+-]?([-+]?\d+){1}(,\d{3})*)?"然而,上面的代码产生了一个逻辑错误,其中只返回最右边的最小(非贪婪)匹配。输出如下:
In [0]: print(re.findall(r"(,\d{3})*", "123,456")) # Expected output: ',456'
Out[0]: [',456', '']
In [1]: print(re.findall(r"(,\d{3})*", "123,456,789")) # Expected output: ',456,789'
Out[1]: [',789', '']
In [2]: print(re.findall(r"(,\d{3})*", "123,456,789,000")) # Expected output: ',456,789,000'
Out[2]: [',000', '']请帮我找出我的错误。
发布于 2021-07-10 08:07:00
使用正则表达式字符串开始\A仅查找第一个匹配项。
number = '123,456,789'
all_after_first_comma = re.sub('\A\d{1,3},', ',', number)获取“,456,789”
发布于 2021-07-10 08:15:55
您可以简单地向您的模式添加一个?:来抑制子组,从而使模式成为(?:,\d{3})*
import re
for result in filter(None, re.findall("(?:,\d{3})*", "123,456,789")):
print(result)输出:
,456,789filter用于过滤掉空字符串。
https://stackoverflow.com/questions/68323671
复制相似问题