I want to detect whether a word is in a sentence using python regex. Also, want to be able to negate it.
import re
re.match(r\'(?=.*\\bfoo\\b)\', \'bar red f
To detect if a word exists in a string you need a positive lookahead:
(?=.*\bfoo\b)
The .* is necessary to enable searching farther than just at the string start (re.match anchors the search at the string start).
To check if a string has no word in it, use a negative lookahead:
(?!.*\bbar\b)
^^^
So, combining them:
re.match(r'(?=.*\bfoo\b)(?!.*\bbar\b)', input)
will find a match in a string that contains a whole word foo and does not contain a whole word bar.