我想字符串搜索如何搜索字符串中的單詞(完全匹配)?
>>>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看時,我想真。我究竟做錯了什麼?
我想字符串搜索如何搜索字符串中的單詞(完全匹配)?
>>>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看時,我想真。我究竟做錯了什麼?
你想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
。
我不認爲in
做正則表達式搜索。請參考re
模塊。
目前還不清楚是什麼你實際上是試圖做的,但如果你想知道「這個」是「研究這個」,這樣做:
"this" in "researching this"
(或)
str1 in str3
或者,如果你想找到它,因爲只有整個單詞,做:
"this" in "researching this".split()
的結果是,它會分裂「研究這個」輸入["researching", "this"]
,然後檢查它中的確切單詞「this」。所以,這是錯誤的:
"this" in "researching thistles".split()
我認爲這個想法是爲了解釋詞邊界以確保找到完全匹配(例如,'研究薊'中的str1'應該返回'False')。 – 2011-10-03 23:31:25
它看起來像你想使用正則表達式,但你使用普通的字符串方法。你需要使用的方法在re
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>
對於Python正則表達式,使用re
模塊:
>>> 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
import re
str1 = 'this'
str2 = 'researching this'
str3 = 'researching this '
if re.search("[^a-z]"+str1+"[^a-z]", str2):
print "found!"
if re.search("[^a-z]"+str1+"[^a-z]", str3):
print "found!"
使用re
模塊。 re
模塊是您應該使用的模塊。 re
岩石。
你是對的。 \ b是我正在尋找的。 – Zenvega