简体   繁体   English

python fnmatch.fnmatch("[seq]") 转义不起作用

[英]python fnmatch.fnmatch("[seq]") escape not working

According to the https://bugs.python.org/issue13929 , "[seq]" should be escaped by the backslash.根据https://bugs.python.org/issue13929 ,“[seq]”应该用反斜杠转义。 However, when i run the same code, i have different result like bellow但是,当我运行相同的代码时,我会得到不同的结果,如下所示

在此处输入图像描述

I need to detect the string contains the "[" and "]".我需要检测包含“[”和“]”的字符串。 So, my solution is to change "[seq]" to the "{seq}" on both string and pattern like bellow.因此,我的解决方案是将字符串和模式上的“[seq]”更改为“{seq}”,如下所示。

string = string.replace("[", "{").replace("]", "}")
pattern = pattern.replace("[", "{").replace("]", "}")
fnmatch.fnmatch(string, pattern)

Could there be a better solution?有没有更好的解决方案?

fnmatch does not support escaping with backslashes. fnmatch不支持带反斜杠的 escaping。 Instead, you should enclose special characters in square brackets.相反,您应该将特殊字符括在方括号中。 From the docs :文档

For a literal match, wrap the meta-characters in brackets.对于文字匹配,将元字符括在括号中。 For example, '[?]' matches the character '?'.例如,'[?]' 匹配字符 '?'。

pattern = "*[[]Ver.2]*"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM