2011-10-03 158 views

回答

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

+0

你是對的。 \ b是我正在尋找的。 – Zenvega

0

我不認爲in做正則表達式搜索。請參考re模塊。

目前還不清楚是什麼你實際上是試圖做的,但如果你想知道「這個」是「研究這個」,這樣做:

"this" in "researching this" 

(或)

str1 in str3 

或者,如果你想找到它,因爲只有整個單詞,做:

"this" in "researching this".split() 

的結果是,它會分裂「研究這個」輸入["researching", "this"],然後檢查它中的確切單詞「this」。所以,這是錯誤的:

"this" in "researching thistles".split() 
+0

我認爲這個想法是爲了解釋詞邊界以確保找到完全匹配(例如,'研究薊'中的str1'應該返回'False')。 – 2011-10-03 23:31:25

1

它看起來像你想使用正則表達式,但你使用普通的字符串方法。你需要使用的方法在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> 
+0

謝謝。如果我想使用're.search(「[^ a-z]」+'researching'+「[^ a-z]」str3)'來搜索'researching',我沒有得到任何對象值。我究竟做錯了什麼? – Zenvega

+0

@Pradeep看到我的答案中涉及'\ b'的部分。 – robert

0

對於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 
0
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!" 
0

使用re模塊。 re模塊是您應該使用的模塊。 re岩石。

相關問題