如何在字符串中查找一个单词(精确匹配)?
我正在尝试进行子字符串搜索
>>>str1 = 'this'
>>>str2 = 'researching this'
>>>str3 = 'researching this '
>>>"[^a-z]"+str1+"[^a-z]" in str2
False
>>>"[^a-z]"+str1+"[^a-z]" in str3
False
我希望在查找str3时能得到True。我哪里做错了呢?
6 个回答
0
我觉得 in
不是用来做正则表达式搜索的。
你可以看看 re
这个模块。
你想要做的事情不太清楚,但如果你想知道 "this" 是否在 "researching this" 里面,可以这样做:
"this" in "researching this"
(或者)
str1 in str3
如果你只是想找 "this" 作为一个完整的单词,可以这样做:
"this" in "researching this".split()
这样做的结果是,它会把 "researching this" 拆分成 ["researching", "this"]
,然后检查里面是否有完整的单词 "this"。所以,这个结果是 False:
"this" in "researching thistles".split()
1
看起来你想使用正则表达式,但你现在用的是普通的字符串方法。你需要使用re
模块里的方法:
import re
>>> re.search("[^a-z]"+str1+"[^a-z]", str2)
>>> re.search("[^a-z]"+str1+"[^a-z]", str3)
<_sre.SRE_Match object at 0x0000000006C69370>
6
你想要使用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
我觉得你其实是在找单独的“this”这个词,而不是带有其他字符的“this”。如果是这样的话,你应该使用单词边界的转义序列\b
。