(该死,乔恩击败了我。哦,好了,你还是可以看一下例子)
就像其他人所说的那样,正则表达式并不是这项工作的最佳工具。如果使用文件路径,请查看os.path。
至于不想要的文件过滤,if 'thumb' not in filename: ...
请在解剖路径后执行操作(其中filename
是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'