Skip to main content
 首页 » 编程设计

python之正则表达式表现出意外

2025年05月04日22mfryf

脚本:

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 

有很多我不明白的地方,对于初学者来说,每个字符串在这个输出中被搜索了四次,有的返回两次作为找到的匹配项,有的返回 3 次。我不确定我的代码中有什么问题导致了这种情况发生,但有人可以尝试看看问题出在哪里吗?

预期的输出是这样的:

Match found: hey 
Match found: hello there 
Match not found: this should not match 
Match found: oh, hiya 

请您参考如下方法:

这不是行为不正确,而是你对 re.search(...) 的误解。

查看输出后的评论:

Match not found: hey                    # because 'hello' is not in 'hey' 
Match found: hey                        # because 'hey' is in 'hey' 
Match not found: hey                    # because 'hi' is not in 'hey' 
Match not found: hey                    # because 'hiya' is not in 'hey' 
 
Match found: hello there                # because 'hello' is in 'hello there' 
Match not found: hello there            # because 'hey' is not in 'hello there' 
Match not found: hello there            # because 'hi' is not in 'hello there' 
Match not found: hello there            # because 'hiya' is not in 'hello there' 
 
Match not found: this should not match  # because 'hello' is not in 'this should not match' 
Match not found: this should not match  # because 'hey' is not in 'this should not match' 
Match found: this should not match      # because 'hi' is in 'this should not match' 
Match not found: this should not match  # because 'hiya' is not in 'this should not match' 
 
Match not found: oh, hiya               # because 'hello' is not in 'oh, hiya' 
Match not found: oh, hiya               # because 'hey' is not in 'oh, hiya' 
Match found: oh, hiya                   # because 'hi' is in 'oh, hiya' 
Match found: oh, hiya                   # because 'hiya' is in 'oh, hiya' 

如果您不想在输入oh, hiya 时匹配模式hi,您应该将单词边界环绕在您的模式周围:

\bhi\b 

这将导致它只匹配出现的 hi not 被其他字母包围(well hiya there不会匹配模式\bhi\b,但是你好会)。