【问题标题】:how to match all 3 digit except a particular number如何匹配除特定数字以外的所有 3 位数字
【发布时间】:2015-08-09 19:11:56
【问题描述】:

我如何匹配除一个特定整数(例如 914)之外的所有 3 位整数。

获取所有 3 位整数很简单 [0=9][0-9][0-9]

尝试[0-8][0,2-9][0-3,5-9] 之类的方法会从集合中删除更多整数,而不仅仅是 914。

我们如何解决这个问题?

【问题讨论】:

    标签: python regex regex-negation


    【解决方案1】:

    您可以使用否定前瞻来添加异常:

    \b(?!914)\d{3}\b
    

    单词边界\b 确保我们匹配一个数字作为一个完整的单词。

    regex demoIDEONE demo

    import re
    p = re.compile(r'\b(?!914)\d{3}\b')
    test_str = "123\n235\n456\n1000\n910 911 912 913\n  914\n915 916"
    print(re.findall(p, test_str))
    

    输出:

    ['123', '235', '456', '910', '911', '912', '913', '915', '916']
    

    【讨论】:

    • 您接受的答案也将匹配较长数字内的数字,例如it will match 911 in 9114。使用.match(),它只会找到字符串开头的数字。使用我的方法,您将在带有.findall() 的较长字符串中找到所有 3 位数字。
    【解决方案2】:

    使用'|' 允许多种模式:

    [0-8][0-9][0-9]|9[02-9][0-9]|91[0-35-9]
    

    例如:

    >>> import re
    >>> matcher = re.compile('[0-8][0-9][0-9]|9[02-9][0-9]|91[0-35-9]').match
    >>> for i in range(1000):
    ...     if not matcher('%03i' % i):
    ...         print i
    ... 
    914
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-29
      • 1970-01-01
      • 2013-04-25
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多