pd176
pd176

Reputation: 841

python exact substring match

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

Upvotes: 3

Views: 2818

Answers (2)

itsafire
itsafire

Reputation: 6083

You could write:

if dish in sentence.split():

This splits sentence by space into a list and looks for a dish in the list of words.

Upvotes: 2

vks
vks

Reputation: 67968

What you need is re.search with \b.

import re
if re.search(r"\b"+dish+r"\b",sentence):

Upvotes: 5

Related Questions