如何在python中检查字符串中的精确单词
基本上我需要找到一种方法来找出在字符串中找到精确单词的方法.我在网上阅读的所有信息都只告诉了我如何在字符串中搜索字母,所以
Basically I need to find a way to figure out a way to find the EXACT word in a string. All the information i have read online has only given me how to search for letters in a string so
98787这是正确的
仍然会在 if 语句中返回为真.
will still come back as true in an if statement.
这是我目前所拥有的.
elif 'This is correct' in text:
print("correct")
这将适用于 Correct 之前的任何字母组合...例如 fkrjCorrect、4123Correct 和 lolcorrect 在 if 语句中都将返回为真.当我希望它仅在它与这是正确的"完全匹配时才返回真实
This will work with any combination of letters before the Correct... For example fkrjCorrect, 4123Correct and lolcorrect will all come back as true in the if statement. When I want it to come back as true only IF it exactly matches "This is correct"
您可以使用正则表达式的词边界.示例:
You can use the word-boundaries of regular expressions. Example:
import re
s = '98787This is correct'
for words in ['This is correct', 'This', 'is', 'correct']:
if re.search(r'\b' + words + r'\b', s):
print('{0} found'.format(words))
结果:
is found
correct found
EDIT:对于完全匹配,将 \b
断言替换为 ^
和 $
以限制匹配到行首和行尾.
EDIT: For an exact match, replace \b
assertions with ^
and $
to restrict the match to the begin and end of line.