-1
re.search('python', 'Working on python is easy')

Here I am able to search python.

I want negative pattern to be placed which actually should result nothing or no match.

I like to use re.search when string contains python but doesn't contain easy in string 'Working on python is easy'. How would I do that? Both positive and negative condition at the same time.

3
  • May be this will help - stackoverflow.com/questions/406230/… Commented Jan 27, 2021 at 19:34
  • What's wrong with not re.search(...)? Commented Jan 27, 2021 at 19:45
  • I like to use re.search when string contains python but doesn't contain easy in string 'Working on python is easy'. How would I do that? Both positive and negative condition at the same time. Commented Jan 28, 2021 at 7:28

1 Answer 1

3

You could use the if statement so that the match object only return True if easy is not given.

For example :

import re
if re.search('python', 'Working on python is easy') and not re.search('easy', 'Working on python is easy'):
    print("found a match")

Some additional sources which may help you:

Python: How to use RegEx in an if statement?

https://docs.python.org/3/library/re.html#match-objects

How to use RegEx in an if statement in Python?

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

2 Comments

Thanks. But I don't want with if condition as I will have list of patterns. some will have only positive search and some may have both positive and negative search and that can also have multiple strings to be searched and not to be searched. So if condition i think, will not work.
I think it will, you may have to put that than a bit more precise in your question. It could work in combination with lists. But now please specify your question.

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.