(该死,乔恩打败了我。哦,好吧,无论如何你可以看看例子)
就像其他人所说的那样,正则表达式不是这项工作的最佳工具。如果您正在使用文件路径,请查看os.path。
至于过滤您不想要的文件,您可以if 'thumb' not in filename: ...
在剖析路径后执行(其中filename
a str
)。
对于后代,这是我对这些正则表达式的看法。r".*(?!thumb).*"
不起作用,因为.*
它是贪婪的,并且前瞻的优先级很低。看看这个:
>>> re.search('(.*)((?!thumb))(.*)', '/tmp/somewhere/thumb').groups()
('/tmp/somewhere/thumb', '', '')
>>> re.search('(.*?)((?!thumb))(.*)', '/tmp/somewhere/thumb').groups()
('', '', '/tmp/somewhere/thumb')
>>> re.search('(.*?)((?!thumb))(.*?)', '/tmp/somewhere/thumb').groups()
('', '', '')
最后一个很奇怪……
另一个正则表达式 ( r"^(?!.*thumb).*"
) 之所以有效,是因为.*
它位于前瞻内部,因此您不会遇到任何字符被盗的问题。您实际上甚至不需要^
,这取决于您使用的是re.match
还是re.search
:
>>> re.search('((?!.*thumb))(.*)', '/tmp/somewhere/thumb').groups()
('', 'humb')
>>> re.search('^((?!.*thumb))(.*)', '/tmp/somewhere/thumb').groups()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'groups'
>>> re.match('((?!.*thumb))(.*)', '/tmp/somewhere/thumb').groups()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'groups'