max max - 5 months ago 18
Python Question

python regex to detect a word exists

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 foo here')

this code works but I do not understand why I need to put
in there.
Also to negate it, I do not know how to do that.
I've tried:

re.match(r'(?!=.*\bfoo\b)', 'bar red foo here')

but it does not work.
My ultimate goal is to combine them like so:

re.match(r'(?=.*\bfoo\b)(?!=.*\bbar\b)', 'bar red foo here')


To detect if a word exists in a string you need a positive lookahead:


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:


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.