Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python regex match string does not start with

Tags:

python

regex

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)

like image 332
WebQube Avatar asked Dec 03 '22 15:12

WebQube


2 Answers

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

like image 87
Idos Avatar answered Dec 20 '22 18:12

Idos


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':
like image 45
TigerhawkT3 Avatar answered Dec 20 '22 19:12

TigerhawkT3