简体   繁体   English

Python fnmatch否定匹配行为不符合预期

[英]Python fnmatch negative match does not behave as expected

trying to match the strings that does not containt "foo" or "bar". 尝试匹配不包含“ foo”或“ bar”的字符串。

After many reserch I came up with something that works with in linux kiki (which is ironically written in python) but does not work when I use it in python: 经过多次研究后,我想出了一些可以在linux kiki使用的东西(讽刺地用python写),但是当我在python中使用它时却不起作用:

Python 3.3.2+ (default, Feb 28 2014, 00:52:16) 
[GCC 4.8.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import fnmatch, re
>>> regex = fnmatch.translate("\Abla.bla.bla-((?!foo|bar).)*\Z")
>>> reobj = re.compile(regex)
>>> reobj.match('bla.bla.bla-9.9.9-123.tar.gz')
>>> reobj.match('bla.bla.bla-9.9.9-123.foo.tar.gz')
>>> reobj.match('bla.bla.bla-9.9.9-123.bar.tar.gz')

I would have expected the first occurence of reobj.match to return a positive match. 我本来希望reobj.match的第一次出现会返回一个正匹配。

Please help me find where I messed up. 请帮助我找到我搞砸的地方。

Thanks 谢谢

The pattern you specify here: 您在此处指定的模式:

regex = fnmatch.translate("\Abla.bla.bla-((?!foo|bar).)*\Z"

is a regular expression pattern, not a shell-style fnmatch pattern. 正则表达式模式,而不是shell样式的fnmatch模式。 fnmatch, of course, only understands the latter. fnmatch当然只了解后者。

Shell-style matching is rather limited. 壳式匹配非常有限。 To do what you want, I'd perhaps just use a regular expression, or strip the "bla.bla.bla-" prefix off of the filename and then check that "foo" not in stripped_filename and "bar" not in stripped_filename . 要执行您想要的操作,我可能只是使用一个正则表达式,或者从文件名中删除"bla.bla.bla-"前缀,然后检查"foo" not in stripped_filename"bar" not in stripped_filename

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

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