2014-02-19 42 views
-1

所以我得到這樣的客戶端文件(4行顯示如下)搜索不包含#instagram_h1和#instagram_h2但應該包含#instagram_h3

Some text #instagram_h1 #instagram_h2 some more text #instagram_h3 more texts 
Some text #instagram_h3 #instagram_h2 some more text #instagram_h1 more texts 
Some text #instagram_h2 some more text #instagram_h3 more texts 
Some text some more text #instagram_h3 more texts 

我找只搜索行線,包含#instagram_h3並放棄包含#instagram_h1和#instagram_h2中的任何一個或兩者的行。 #instagram_h3將永遠在場。

我嘗試:

h1 = '#instagram_h1' 
h2 = '#instagram_h2' 
h3 = '#instagram_h3' 
result = re.search(r"(!h1|!h2)", str) 
print result 

這裏結果總是無。任何人都可以請解釋,我做錯了什麼?

+0

解釋downvote? – NullException

回答

1

運算符沒有正則表達式!。你可以做的是找到包含這些字符串,然後排除它們。

if re.search(r"#instagram_(h1|h2)\b", str): 
    # no good! 

注意如何我添加\b,以防止類似#instagram_h123從匹配。

或者,對於像這樣的簡單搜索,您可以跳過正則表達式並直接檢查子字符串。

if '#instagram_h1' in str or '#instagram_h2' in str: 
    # no good! 

# or 

hashtags = ['#instagram_h1', '#instagram_h2'] 
if any(hashtag in str for hashtag in hashtags): 
    # sorry! 

注意,這些簡單的測試將匹配#instagram_123#instagram_234,這可能不是你想要的。

+0

來自Perl的背景,我認爲python有! (反轉)。激情學會了。 – NullException