Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a single regex rather than a nested statement

I want to do the following match:

match if MBzz is in the string but not if [Rr][Ee][Ff] is in the string

So the following should match:

  • klasdlkMBzzsdld
  • MBzz

And the following should not match:

  • RefmmmmMBzzmmmmm
  • MBzzmmmmmmREFmmmm

etc.

For now, I am doing this terrible hack:

def mySearch(val):
    if (re.compile('MBab').search(val) is not None) and \
       (re.compile('[Rr][Ee][Ff]').search(val) is None):
        return re.compile('MBab').search(val).group()
    return None

However, I feel that for something that is as simple as this, I should be able to accomplish this as a one liner.

like image 513
ssm Avatar asked Jan 23 '26 11:01

ssm


1 Answers

You can use following regex with modifier i for ignoring the case :

^(?:(?!ref).)*(?=MBzz)(?:(?!ref).)*$

Demo

regex=re.compile(r'^[^ref]*(?=MBzz)[^ref]*$',re.I|re.MULTILINE)

The positive look behind (?=MBzz) will ensure your regex engine that your string contains MBzz and following negative look behind (?:(?!ref).)* will match any thing except ref.

And if you want yo consider the case for MBzz you can use following regex without ignore case modifier :

^(?:(?![rR][eE][fF]).)*(?=MBzz)(?:(?![rR][eE][fF]).)*$
like image 135
Mazdak Avatar answered Jan 25 '26 01:01

Mazdak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!