WebQube
WebQube

Reputation: 8961

python regex match string does not start with

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.* 

regex here

Now I want to reverse that condition, for example:

Please 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

Answers (4)

WebQube
WebQube

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

Idos
Idos

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

TigerhawkT3
TigerhawkT3

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

Hidde
Hidde

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

Related Questions