Reputation: 8961
I want to match any string that does not start with 4321 I came about it with the positive condition: match any string that starts with 4321:
^4321.*
Now I want to reverse that condition, for example:
1234555
passes12322222
passessNone
passess4321ZZZ
does not pass43211111
does not passPlease help me find the simplest regex as possible that accomplishes this.
I am using a mongo regex but the regex object is build in python so please no python code here (like startswith
)
Upvotes: 5
Views: 24074
Reputation: 8961
Thank, @idos. For a complete answer I used the mongo's
$or opertator
mongo_filter = {'$or': [{'db_field': re.compile("^(?!4321).*$")}, {'db_field1': {'$exists': False}}]})
This ensure not only strings that starts with 4321 but also if the field does not exists or is None
Upvotes: 0
Reputation: 15310
You could use a negative look-ahead (needs a multiline modifier):
^(?!4321).*
You can also use a negative look-behind (doesn't match empty string for now):
(^.{1,3}$|^.{4}(?<!4321).*)
Note: like another answer stated, regex is not required (but is given since this was the question verbatim) -> instead just use if not mystring.startswith('4321')
.
Edit: I see you are explicitly asking for a regex now so take my first one it's the shortest I could come up with ;)
Upvotes: 19
Reputation: 49320
You don't need a regex for that. Just use not
and the startswith()
method:
if not mystring.startswith('4321'):
You can even just slice it and compare equality:
if mystring[:4] != '4321':
Upvotes: 7
Reputation: 11911
Why don't you match the string, and negate the boolean value using not
:
import re
result = re.match('^4321.*', value)
if not result:
print('no match!')
Upvotes: 0