列出给定正则表达式/一组扩展名的目录中的所有文件(Matlab) [英] List all files in a directory given a regular expression / a set of extensions (Matlab)

查看:126
本文介绍了列出给定正则表达式/一组扩展名的目录中的所有文件(Matlab)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正则表达式定义感兴趣的文件名.列出符合此条件的目录中所有文件的最佳方法是什么?

I have a regular expression defining the filenames of interest. What is the best way to list all files in a directory that match this condition?

我对此的尝试是:

f = dir(DIR);
f = {f([f.isdir] == 0).name};
result = f(~cellfun(@isempty, regexpi(f, '.*(avi|mp4)')));

但是,我想知道是否有更快,更清洁的解决方案?

However, I wonder if there is a faster and/or cleaner solution to this?

如果不是正则表达式而是仅列出了可能的文件扩展名,是否可以简化它?

Is is possible to simplify it if instead of a regular expression I have only a list of possible file extensions?

推荐答案

基本上,您的方法就是我想要的.但是,您的代码行可以简化为(目录丢失在正则表达式中,并且在最后的连接中为空单元格):

Fundamentally your approach is what I would go for. However, your lines of code can be simplified to (directories are lost in the regex and empty cells in the final concatenation):

f = dir('C:\directory');
f = regexpi({f.name},'.*txt|.*pdf','match');
f = [f{:}];

此外,请注意,函数dir()接受通配符(*),但不支持多个扩展名:

Also, note that the function dir() accepts wildcards (*) but not multiple extensions:

dir('C:\directory\*.avi')

这意味着您只能立即检索与扩展名匹配的那些文件,但是您必须循环以获取扩展名的数量:

This means you can retrieve immediately only those files that match an extension, however you have to loop for the number of extensions:

d   = 'C:\users\oleg\desktop';
ext = {'*.txt','*.pdf'};
f   = [];
for e = 1:numel(ext)
    f = [f; dir(fullfile(d,ext{e}))];
end

替代(不推荐)

ext = {'*.txt','*.pdf'};
str = ['!dir ' sprintf('%s ',ext{:}) '/B'];
textscan(evalc(str),'%s','Delimiter','')

其中str!dir *.txt *.pdf /B,而evalc()捕获字符串的求值并textscan()解析它.

where str is !dir *.txt *.pdf /B and evalc() captures the evaluation of the string and textscan() parses it.

这篇关于列出给定正则表达式/一组扩展名的目录中的所有文件(Matlab)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆