Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python exact substring match

Tags:

python

regex

I have a list of dishes and a sentence.

I want to check if a dish is present in the sentence. However, if I do a normal

if dish in sentence:

I will basically get a substring matching. My problem is that say I have a

dish='puri'
sentence='the mutton shikampuri was good'

the above code still matches puri with shikampuri which i don't want.

If I try tokenizing the sentence, I will not be able to match dishes like dish='puri bhaji'

Is there any way I can ignore the matches which don't begin with my dish string? Basically, I want to ignore patterns like 'shikampuri' when my dish is 'puri'.

like image 633
pd176 Avatar asked Feb 28 '26 17:02

pd176


1 Answers

What you need is re.search with \b.

import re
if re.search(r"\b"+dish+r"\b",sentence):
like image 172
vks Avatar answered Mar 03 '26 06:03

vks



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!