脚本:
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
有很多事情我不明白,对于初学者来说,每个字符串在这个输出中被搜索四次,一些返回两个作为找到的匹配,一些返回三个。我不确定我的代码中有什么问题导致这种情况发生,但是有人可以尝试看看有什么问题吗?
预期的输出是这样的:
Match found: hey
Match found: hello there
Match not found: this should not match
Match found: oh, hiya