How to match all 3 digits except a specific number

How can I match all three-digit integers except one specific integer, for example 914.

Getting all three-digit integers is quite simple [0=9][0-9][0-9]

Trying to do something like [0-8][0,2-9][0-3,5-9] removes more integers from the set except 914.

How do we solve this problem?

+4
source share
2 answers

Use '|' to allow multiple patterns:

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

For instance:

 >>> 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 
+1
source

You can use a negative forecast ahead to add an exception:

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

The word boundary \b ensures that we match the number as a whole word.

Watch the regex demo and IDEONE 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)) 

Output:

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

All Articles