How to return a sentence with an exact word not as a part of the other word

I need to find all sentences with exact word match. Not inside of the other words.

I’m trying this:
text='He's using apple phone. I like apples. Did you install this app? Apply today!'

[sentence + '.' for sentence in text.split('.') if 'app' in sentence]

I get the output:
'He's using apple phone. I like apples. Did you install this app? Apply today!'

but need only:
Did you install this app?

>Solution :

To find all sentences with an exact word match, you can use word boundaries in your search query. In Python, you can use the re module to search for regular expressions.

import re

text = "He's using apple phone. I like apples. Did you install this app? Apply today!"

# Use regex to find sentences with the exact word "app"
pattern = r'\bapp\b'
matches = re.findall(pattern, text)

# Split the text into sentences and only keep the ones with a match
sentences = text.split('.')
result = [sentence.strip() + '.' for sentence in sentences if re.search(pattern, sentence)]

print(result)

This code should output [‘Did you install this app?’]

Note that we’re using the re.search method instead of in to search for the word "app" with word boundaries (\b). This ensures that we only match the exact word and not words that contain "app" as a substring.

Leave a Reply