You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何将正则匹配对象与列表进行比较?

问题分析与解决

嘿,我一眼就瞅出问题在哪了!你代码里的if match3 in x判断为啥没生效?因为**match3是正则匹配出来的SRE_Match对象,不是实际的字符串内容**,直接拿它和列表x里的字符串比,肯定永远不相等,那个pass根本不会触发,所以指令词也被当成ID输出了。

修正方案

你得调用匹配对象的group()方法,拿到它实际匹配到的字符串,再和x里的元素做对比。把第三个for循环的判断条件改成这样:

if match3.group() in x:
    pass
else:
    print("ID: ")
    print(match3)

完整修正后的代码

import re
x = ["Set","Sets","ShowSets","Union","Intersect","SetUnion","SetIntersect"]
print(x)
while True:
    text_to_search = input('Introduce an instruction: ')
    for match1 in re.finditer('Sets?|ShowSet|ShowSets|Union|Intersect|SetUnion|SetIntersect', text_to_search):
        print("Instruction: ")
        print(match1)
    for match2 in re.finditer(r':=|{|}|;', text_to_search):
        print("Operator: ")
        print(match2)
    for match3 in re.finditer(r'[a-zA-Z0-9]+', text_to_search):
        if match3.group() in x:
            pass
        else:
            print("ID: ")
            print(match3)
    print(x)

验证效果

当你输入Set Hi时,输出就会和你预期的一致:

Introduce an instruction: Set Hi
Instruction: 
<_sre.SRE_Match object; span=(0, 3), match='Set'>
ID: 
<_sre.SRE_Match object; span=(4, 6), match='Hi'>
['Set', 'Sets', 'ShowSets', 'Union', 'Intersect', 'SetUnion', 'SetIntersect']

内容的提问来源于stack exchange,提问作者Sebas Silva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:58:33