如何编写一个正则表达式来匹配每三位数字中带有逗号的数字?

2024-09-30 12:13:32 发布

您现在位置:Python中文网/ 问答频道 /正文

必须符合以下条件:

  • '42'

  • “1234”

  • '6368745'

但不包括以下内容:

  • '12,34567'(逗号之间只有两个数字)

  • “1234”(缺少逗号)

我用python3编写了以下python程序。我做错什么了?它给了AttributeError

import re
numRegx = re.compile(r"""^
(\d{1,3}(\,))? # optional first three digits and comma (1,)
((d{3})(\,))*  # optional Second three digits and comma (345,)
\d{3}$         # Last three digits (456)
""", re.VERBOSE)
mo = numRegx.search('1,345,456')
print(mo.group())

Tags: andimport程序re数字条件optionalpython3
3条回答

这应该行得通。在

正则表达式:

^(\d{1,3}(?:,\d{3})*)$

JavaScript代码:

和13;

和13;

输入:

42
1,234
6,368,745
12,34,567
9999999,123

输出:

42
1,234
6,368,745

参见:https://regex101.com/r/oq67pb/2

这里的答案可能对你的需要有用

(:?^|\s)(?=.)((?:0|(?:[1-9](?:\d*|\d{0,2}(?:,\d{3})*)))?(?:\.\d*[1-9])?)(?!\S)

这是对类似问题的公认答案:

Regular expression to match numbers with or without commas and decimals in text

试试这个:

^(\d{1,3})(,\d{3})*$

https://regex101.com/r/Dy83Jv/1

相关问题 更多 >

    热门问题