-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.

Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37
  • May be this will help - https://stackoverflow.com/questions/406230/regular-expression-to-match-a-line-that-doesnt-contain-a-word – rootkonda Jan 27 '21 at 19:34
  • What's wrong with `not re.search(...)`? – kaya3 Jan 27 '21 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. – user14613954 Jan 28 '21 at 07:28

1 Answers1

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?

grumpyp
  • 432
  • 4
  • 10
  • 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. – user14613954 Jan 28 '21 at 08:20
  • 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**. – grumpyp Jan 28 '21 at 08:32