首页 > 解决方案 > 如何在一个命令中传递不敏感的标志以匹配?

问题描述

我正在对带有编译模式后面标志的几个键进行不区分大小写的匹配:

def case(string):
    switcher = {
        re.compile('bronze', re.IGNORECASE):10,
        re.compile('carbon', re.IGNORECASE):16,
    }
    for i in switcher.keys():
        if re.match(i, string):
            return switcher[i]
    return "Invalid: " + string

有没有更聪明的方式来传递标志,所以我不必在每一行都指定它?

标签: python

解决方案


你根本不必使用re.compile,真的。re.match和朋友无论如何都会在内部缓存最后使用的正则表达式模式。

在这里,switcher已从case函数中重构出来,因此不会在每次调用时重新计算;此外,我们dict.items()用于同时获取模式和值。

switcher = {
    'bronze': 10,
    'carbon': 16,
}

def case(string):
    for pattern, value in switcher.items():
        if re.match(pattern, string, flags=re.IGNORECASE):
            return value
    return "Invalid: " + string

但是,根据您的示例,尚不清楚您是否需要正则表达式,或者您是否只需要不区分大小写的子字符串匹配,在这种情况下,将测试字符串小写在计算上会更便宜,然后只需使用if str1 in str2,就像这样(假设与switcher上一个示例中的 dict 相同。)

def case_no_re(string):
    l_string = string.lower()
    for pattern, value in switcher.items():
        if pattern in l_string:
            return value
    return "Invalid: " + string

推荐阅读