你会如何编写一个与每三位数用逗号匹配的正则表达式?

时间:2017-02-17 14:00:43

标签: python regex

必须符合以下条件:

  • ' 42'

  • ' 1234'

  • ' 6368745'

但不是以下内容:

  • ' 12,34,567' (逗号之间只有两位数字)

  • ' 1234' (缺少逗号)

我在python 3中编写了以下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())

3 个答案:

答案 0 :(得分:5)

试试这个:

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

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

答案 1 :(得分:2)

这应该有效。

正则表达式:

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

JavaScript代码:

const regex = /^(?:\d{1,3}(?:,\d{3})*)$/gm;
const str = `42
1,234
6,368,745
12,34,567`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

输入:

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

输出:

42
1,234
6,368,745

请参阅:https://regex101.com/r/oq67pb/2

答案 2 :(得分:1)

此处的答案可能对您的需求有用,请查看已接受答案的底部

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