简体   繁体   English

如何正确使用 Pathlib 中的正则表达式?

[英]How to work with regex in Pathlib correctly?

I want find all images and trying to use pathlib, but my reg expression don't work.我想找到所有图像并尝试使用 pathlib,但我的 reg 表达式不起作用。 where I went wrong?我哪里出错了?

from pathlib import Path
FILE_PATHS=list(Path('./photos/test').rglob('*.(jpe?g|png)'))
print(len(FILE_PATHS))
FILE_PATHS=list(Path('./photos/test').rglob('*.jpg'))#11104
print(len(FILE_PATHS))

0
11104

Get list of files using Regex使用正则表达式获取文件列表

import re
p = Path('C:/Users/user/Pictures')
files = []
for x in p.iterdir(): 
    a = re.search('.*(jpe?g|png)',str(x))
    if a is not None:
        files.append(a.group())

Get list of files using pathlib.Path then filter list with regex using re使用pathlib.Path获取文件列表,然后使用re使用正则表达式过滤列表

import re
from pathlib import Path
pattern = '.*(jpe?g|png)'
matching_files = []

for _path in [p for p in basepath.rglob('*.*')]:
    if re.match(pattern, _path.name):
        matching_files.append(_path)

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

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