您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

否定超前断言在python中不起作用

否定超前断言在python中不起作用

(该死,乔恩击败了我。哦,好了,你还是可以看一下例子)

就像其他人所说的那样,正则表达式并不是这项工作的最佳工具。如果使用文件路径,请查看os.path

至于不想要的文件过滤,if 'thumb' not in filename: ...请在解剖路径后执行操作(其中filenamestr)。

为了后代,这是我对那些正则表达式的想法。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'
python 2022/1/1 18:52:08 有311人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶