gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:44:38 27 4
gpt4 key购买 nike

脚本:

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,但是你好)。

关于python - 正则表达式表现出意外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10776631/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com