Create a single regex, not a nested expression

I want to make the following match:

if MBzz

in line, but not if [Rr][Ee][Ff]

in line

So, the following should match:

  • klasdlkMBzzsdld
  • MBzz

And the following shouldn't be the same:

  • RefmmmmMBzzmmmmm
  • MBzzmmmmmmREFmmmm

and etc.

At the moment 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 like for something as simple as this, I would have to do it as one liner.

+3


source to share


1 answer


You can use the following modifier regex i

to ignore the case:

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

      

Demo

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

      



A positive look and feel (?=MBzz)

will ensure that your regex engine containing your string MBzz

, and the subsequent negative look, (?:(?!ref).)*

will match anything except ref

.

And if you want you to consider the case for MBzz

, you can use the following regex without the case code modifier:

^(?:(?![rR][eE][fF]).)*(?=MBzz)(?:(?![rR][eE][fF]).)*$

      

+2


source







All Articles