3

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.

1
  • For some reason, my computer did an autocorrect for regex to reggae Commented Jun 29, 2015 at 17:22

1 Answer 1

2

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]).)*$
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer. Its nearly exactly what I want, except that I do want to match the case for MBzz. But the positive and negative look behinds look very interesting. Ill definitely take a look at them.

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.