使用Python re.findall方法返回列表时遭遇IndexError的问题排查与解决求助
搞定
re.findall的IndexError和匹配失效问题 Hey,我来帮你捋清楚你遇到的两个问题:先是IndexError报错,再是匹配逻辑完全不工作,咱们一步步来修~
1. 为啥会弹出IndexError: list index out of range?
看你贴的第一个代码片段,这里有个超明显的手滑拼写错误!你定义的变量是return_from_findall,结果访问列表元素的时候写成了return_from_finall(少了一个字母d)。要是这个笔误出现在你实际运行的代码里,要么Python会把return_from_finall当成全新的未定义变量报错,要么如果刚好return_from_findall是空列表(没匹配到内容),你又没加判断就硬访问[0],直接就触发索引越界错误了。
先把这个笔误修正,确保变量名完全一致:
return_from_findall = re.findall(regex, input) if return_from_findall: # 这里把变量名改对! print(return_from_findall[0]) if return_from_findall[0] == somestring: print("match found")
2. 匹配逻辑为啥不起作用?
再看你的完整代码,这里藏着两个关键问题:
问题一:搜索的内容和预期内容对不上
你的search_item是不带句号的:
search_item = "Another option is to use the name randomizer"
但expected_list里的第一个元素是带句号的:'Another option is to use the name randomizer.',而output里的目标行也是带句号的!这就导致re.findall根本匹配不到内容,自然进不了if return_from_findall:的分支。
问题二:匹配索引没跟着循环走
你初始化了match = 0,但整个循环里都没给这个变量加1!不管循环到第几行,你都在拿当前行的结果和expected_list[0]比,这肯定没法匹配后面的行啊。
修正后的完整代码
我把这些问题都改了,还加了点小优化,你可以直接跑:
import re output = """ Another option is to use the name randomizer. to randomize all the names on your list. In this case, you arent using it as a random name picker, but as a true name randomizer. For example, """ match_idx = 0 # 把变量名改得更清楚,避免混淆 # 给search_item加上句号,和目标内容完全匹配 search_item = "Another option is to use the name randomizer." expected_list = [ 'Another option is to use the name randomizer.', 'to randomize all the names on your list.', 'In this case, you arent using it as a', 'random name picker, but as a true name', 'randomizer. For example,'] # 先过滤掉空行,避免无效循环 for line in [l.strip() for l in output.splitlines() if l.strip()]: print(" ################### ") return_from_findall = re.findall(search_item, line) print("当前行内容 - ", line) print("匹配结果 - ", return_from_findall) print("预期内容 - ", expected_list[match_idx]) if return_from_findall: # 其实直接用当前行和预期内容比更准确,不用绕findall if line == expected_list[match_idx]: print("✅ 找到匹配啦!") # 每循环一次,索引加1,对应下一个预期元素 match_idx += 1
额外小贴士
- 要是你只是想判断当前行和预期列表的元素是否相等,完全没必要用
re.findall,直接line == expected_list[match_idx]就够了,效率还更高。 - 如果确实需要用正则匹配,记得根据需求调整表达式,比如想忽略句号的话,可以写成
search_item = r"Another option is to use the name randomizer\.?"(用\.?表示句号可选)。
内容的提问来源于stack exchange,提问作者Katta Sivasai
相关产品推荐
相关产品推荐

