腳本:正則表達式表現意外
import re
matches = ['hello', 'hey', 'hi', 'hiya']
def check_match(string):
for item in matches:
if re.search(item, string):
print 'Match found: ' + string
else:
print 'Match not found: ' + string
check_match('hey')
check_match('hello there')
check_match('this should not match')
check_match('oh, hiya')
輸出:
Match not found: hey
Match found: hey
Match not found: hey
Match not found: hey
Match found: hello there
Match not found: hello there
Match not found: hello there
Match not found: hello there
Match not found: this should not match
Match not found: this should not match
Match found: this should not match
Match not found: this should not match
Match not found: oh, hiya
Match not found: oh, hiya
Match found: oh, hiya
Match found: oh, hiya
有各種各樣的事情,我不明白,對於初學者來說,每個字符串搜索四次在此輸出,一些返回2作爲一個找到的匹配,有三個。我不確定導致這種情況發生的代碼中有什麼問題,但有人可以嘗試查看哪些問題?
的預期結果會是這樣:
Match found: hey
Match found: hello there
Match not found: this should not match
Match found: oh, hiya
你搭配什麼正則表達式反對? –