正则表达式,每三位数字与逗号匹配

时间:2017-04-02 18:18:52

标签: python regex

你会如何编写一个与每三位数用逗号匹配的正则表达式?它必须符合以下条件:'42','1,234'和'6,368,745'。

但不是以下内容:'12,34,567'(逗号之间只有两位数),'1234'(缺少逗号)。

我知道这个问题之前已经被问过并得到了回答,但这些问题仅适用于传递给正则表达式的字符串是其中一个数字的解决方案。如果正则表达式通过整个字符串'42 1,234 6,368,745 12,34,567 1234',我想知道最好的方法是什么。

我设法通过首先拆分字符串然后循环遍历它来完成它,如下所示:

regexsplit = re.compile(r'^\d{1,3}(,\d{3})*$')
splitstring = string.split()
matches = []

for num in splitstring:
    if regexsplit.search(num) is not None:
        matches.append(regexsplit.search(num).group())

print matches

首先,我想知道是否有更有效的方法来编写代码。其次,我想知道是否有办法在不拆分字符串和使用.findall()方法的情况下执行此操作。我知道你不再能够使用^和$来锚定开头和结尾,所以我已经完成了:

regexnosplit = re.compile(r'(\d{1,3}(,\d{3})*)')
matches2 = []

for groups in regexnosplit.findall(string):
    print groups[0]

然而,我显然仍然得到'12','34,567','123','4'返回,所以我猜我需要通过一个更强大的正则表达式,但我似乎无法找到解决方案。

4 个答案:

答案 0 :(得分:1)

您可以使用

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

Demo and explanation

答案 1 :(得分:0)

我会这样做,试图找到不需要的模式:

import re

s = '42 1,234 6,368,745 12,34,567 1234'

rgx = re.compile(',[0-9]{1,2},|[0-9]{4,}')
nums = [x for x in s.split() if not rgx.search(x)]

print nums  # ['42', '1,234', '6,368,745']

答案 2 :(得分:0)

您可以使用空白边界来匹配正确格式化的
千位逗号。

(?<!\S)\d{1,3}(?:,\d{3})*(?!\S)

解释

 (?<! \S )            # Whitespace boundary
 \d{1,3}              # Required 1-3 digits
 (?: , \d{3} )*       # Optional comma + 3 digits, 0 to many times
 (?! \S )             # Whitespace boundary

测试目标42 1,234 6,368,745 12,34,567 1234

输出

 **  Grp 0 -  ( pos 0 , len 2 ) 
42  

 **  Grp 0 -  ( pos 3 , len 5 ) 
1,234  

 **  Grp 0 -  ( pos 9 , len 9 ) 
6,368,745  

答案 3 :(得分:0)

对我有用的那个:

rgx = re.compile(r'^\d{1,3}(\,\d{3})*$')

您可以在此处查看:https://regex101.com/r/TsTNQm/1

相关问题