Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to match all 3 digit except a particular number

How do i match all 3 digit integers except one particular integer, say 914.

Getting all 3 digit integers is simple enough [0=9][0-9][0-9]

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

How do we solve this problem?

like image 346
Kira Avatar asked Dec 19 '22 01:12

Kira


1 Answers

You can use a negative look-ahead to add an exception:

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

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

See 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']
like image 134
Wiktor Stribiżew Avatar answered Dec 26 '22 12:12

Wiktor Stribiżew