简体   繁体   中英

Python fnmatch negative match does not behave as expected

trying to match the strings that does not containt "foo" or "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:

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.

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. fnmatch, of course, only understands the latter.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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