将2位数字与分隔的逗号匹配(不包括浮动数字)

问题描述 投票:1回答:1

对于每个字符串输入,我只需要匹配一个2位数(或许多)(需要用空格或逗号+空格(不是逗号+数字)分隔)。

在下面的例子中,您会看到一些示例的结果。我不希望我的正则表达式抓住前两个例子。

def cleanse_no(string):
    regex = r"(?:^|\s)(\d{2})\b"
    string = str(string).strip(" .,€")
    list_digits = re.findall(regex, string)
    digits = ", ".join(list_digits)
    return digits

test_digits = ["€ 22.22", ". 23,600.90", "25 45 61", "22, 232, 36, 02,", "1, 23, 456"]
for test_dgt in test_digits:
    print(test_dgt,"-------find_no--------->",cleanse_no(test_dgt))

我得到这些结果:

€ 22.22 -------find_no---------> 22
. 23,600.90 -------find_no---------> 23
25 45 61 -------find_no---------> 25, 45, 61
22, 232, 36, 02, -------find_no---------> 22, 36, 02
1, 23, 456 -------find_no---------> 23

有任何想法吗 ?

python regex
1个回答
2
投票

你可以用

def cleanse_no(s):
    regex = r"(?<!\S)\d{2}(?=,?(?:\s|$))"
    return ", ".join(re.findall(regex, s))

参见Python demoregex demo

图案细节

  • (?<!\S) - 一个空白的左边界
  • \d{2} - 两位数
  • (?=,?(?:\s|$)) - 在当前位置的右边,必须有一个可选的逗号,后跟空格或字符串结尾。
© www.soinside.com 2019 - 2024. All rights reserved.