如何匹配除特定数字之外的所有3位数字

Kir*_*ira 4 python regex regex-negation

如何匹配除一个特定整数之外的所有3位整数,比如914.

获得所有3位数整数非常简单 [0=9][0-9][0-9]

尝试[0-8][0,2-9][0-3,5-9]从914中除去更多的整数.

我们如何解决这个问题?

Wik*_*żew 10

您可以使用负面预测来添加例外:

\b(?!914)\d{3}\b
Run Code Online (Sandbox Code Playgroud)

单词边界\b确保我们将数字匹配为整个单词.

请参阅regex演示IDEONE演示:

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))
Run Code Online (Sandbox Code Playgroud)

输出:

['123', '235', '456', '910', '911', '912', '913', '915', '916']
Run Code Online (Sandbox Code Playgroud)