如何在python中检查字符串中的精确单词 [英] How do I check for an EXACT word in a string in python

查看:32
本文介绍了如何在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.

这篇关于如何在python中检查字符串中的精确单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆