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
相关产品推荐
相关产品推荐

