Im trying to check if all words in list are present in string. This code works for me, but it also matches strings inside words, like if I search for 'cat', it also matches 'category', so I need regex to only match whole words, but just cannot find a way how to do it. I need it return True or False.
are_both_words_present = all(x in normalized_title for x in [question_element[0], question_element[1], question_element[2]])
CodePudding user response:
I think the "\b" is what you are looking for. So the line of code you shared may turn into:
import re
are_both_words_present = all(re.search(r"\b" x r"\b", normalized_title) for x in [question_element[0], question_element[1], question_element[2]])
CodePudding user response:
You can use \b
to signify a word boundary (i.e. whitespace or start/end of string):
>>> import re
>>> test = ('cat', 'category')
>>> for t in test:
... re.match(r'\bcat\b', t)
...
<re.Match object; span=(0, 3), match='cat'>
In this case, only cat
matches, since it's the only string that have cat delimited by two word boundaries.