如何在字符串中搜索单词(精确匹配)?

2024-04-24 03:01:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试子串搜索

>>>str1 = 'this'
>>>str2 = 'researching this'
>>>str3 = 'researching this '

>>>"[^a-z]"+str1+"[^a-z]" in str2
False

>>>"[^a-z]"+str1+"[^a-z]" in str3
False

我想在第三季的时候是真的。我做错什么了?


Tags: infalsethis子串str1str2researchingstr3
3条回答

对于Python中的正则表达式,请使用^{}模块:

>>> import re
>>> re.search("[^a-z]"+str1+"[^a-z]", str2) is not None
False
>>> re.search("[^a-z]"+str1+"[^a-z]", str3) is not None
True

您需要Python的re模块:

>>> import re
>>> regex = re.compile(r"\sthis\s") # \s is whitespace
>>> # OR
>>> regex = re.compile(r"\Wthis\W")
>>> # \w is a word character ([a-zA-Z0-9_]), \W is anything but a word character
>>> str2 = 'researching this'
>>> str3 = 'researching this '
>>> bool(regex.search(str2))
False
>>> regex.search(str3)
<_sre.SRE_Match object at 0x10044e8b8>
>>> bool(regex.search(str3))
True

我有预感你实际上是在找“这个”这个词,而不是“这个”周围有非单词字符。在这种情况下,应该使用单词边界转义序列^{}

看起来您想要使用正则表达式,但是您使用的是普通的字符串方法。您需要使用^{} module中的方法:

import re
>>> re.search("[^a-z]"+str1+"[^a-z]", str2)
>>> re.search("[^a-z]"+str1+"[^a-z]", str3)
<_sre.SRE_Match object at 0x0000000006C69370>

相关问题 更多 >