Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python regex to detect a word exists

Tags:

python

regex

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')
like image 939
max Avatar asked May 09 '26 12:05

max


1 Answers

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.

like image 193
Wiktor Stribiżew Avatar answered May 12 '26 01:05

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!