5

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:

  • 1234555 passes
  • 12322222 passess
  • None passess
  • 4321ZZZ does not pass
  • 43211111 does not pass

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)

4 Answers 4

19

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 ;)

Sign up to request clarification or add additional context in comments.

8 Comments

regex101.com/r/fC1wX4/10 - am I missing something? I'm getting 0 matches even though I should get 2 out of 3 here
It does match, if you add the multiline-modifier to the regex: regex101.com/r/fC1wX4/12
Why do you exclude empty strings?
@CasimiretHippolyte what exactly do you mean? I am matching only strings that don't start with 4321.
|
7

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':

Comments

0

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!')

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.