Is there a way to get full text search matches when using an if in statement?

Viewed 18

I am working with a search problem and I am having issues getting it to work. So here is what I am trying to do:

bus_name = 'GUARDFORCE AI'
description = 'GUARDFORCE AI CO LIMITED AI GFAIW RIVERSOFT INC PEAKWORK COMPANY GFAIS CONCIERGE GUARDFORCE AI RIVERSOFT ROBOT TRAVEL AGENCY'

# # Solution 1
if bus_name in description:
    print('Yes')
else:
    print('No')

If I change bus_name to 'GUARDFORCE A' it will still say 'Yes', but I want it to say 'No'. I am only looking for full matches, not partial. Any ideas how to get this to work?

1 Answers

I would use regular expression matching to do this. Regular expressions let you define that you only want to match whole words. You do this by matching against word boundaries using the '\b' regex term. Here's an illustration of this using the two cases you provide:

import re

description = 'GUARDFORCE AI CO LIMITED AI GFAIW RIVERSOFT INC PEAKWORK COMPANY GFAIS CONCIERGE GUARDFORCE AI RIVERSOFT ROBOT TRAVEL AGENCY'

print('Yes' if re.match(r'\bGUARDFORCE\b\s+\bAI\b', description) else 'No')
print('Yes' if re.match(r'\bGUARDFORCE\b\s+\bA\b', description) else 'No')

Result:

Yes
No

You would likely want to parameterize the creation of the regular expressions you match so that you don't have to duplicate the form of the expression every time. This example is just to show you the basics of how regular expressions work to solve the specific problem you're asking about.

Related