Python中fnmatch.fnmatch对[seq]转义失效,求更优解决方案
更优解决方案
方案1:直接用字符串成员检测(最简便)
如果只是单纯检测字符串中是否包含[或],完全不需要借助fnmatch,直接用Python原生的成员运算符就能搞定,效率最高:
s = "abc[123]def" has_brackets = '[' in s or ']' in s print(has_brackets) # 输出True
方案2:利用fnmatch原生语法匹配字面方括号
fnmatch的字符集规则支持字面匹配方括号:[[]可匹配[,[]]可匹配],不需要依赖有bug的反斜杠转义。如果需要结合通配符使用,比如检测包含方括号的任意字符串:
import fnmatch # 检测是否包含[ print(fnmatch.fnmatch("abc[123]def", "*[[]*")) # 输出True # 检测是否包含] print(fnmatch.fnmatch("abc[123]def", "*[]]*")) # 输出True # 检测是否同时包含[和] print(fnmatch.fnmatch("abc[123]def", "*[[]*[]]*")) # 输出True
方案3:用正则表达式替代fnmatch(灵活可控)
如果需要复杂通配符+方括号匹配,直接用re模块更可靠(fnmatch底层也是转成正则处理)。可以先通过fnmatch.translate()把模式转成正则,再修正方括号的转义逻辑:
import re import fnmatch def match_with_brackets(string, pattern): # 转成fnmatch对应的正则表达式 regex_pattern = fnmatch.translate(pattern) # 将正则中的[]替换为字面匹配的转义形式 regex_pattern = regex_pattern.replace('[', r'\[').replace(']', r'\]') return re.search(regex_pattern, string) is not None # 测试:检测带方括号的字符串是否匹配通配符模式 print(match_with_brackets("abc[123]def", "*[*]*")) # 输出True
内容的提问来源于stack exchange,提问作者mal mal
相关产品推荐
相关产品推荐

