2016-09-27 67 views
0

我的文件名列表中一个结构阵列,例如:如何根据数字字符串提取文件名?

4x1 struct array with fields: 

    name 
    date 
    bytes 
    isdir 
    datenum 

其中files.name

ans = 

ts.01094000.crest.csv 


ans = 

ts.01100600.crest.csv 

我有号码的另一个列表(比如,1094000) 。我想从结构中找到相应的文件名。

请注意,1094000没有前面的0.通常可能有其他数字。所以我想搜索'1094000'并找到这个名字。

我知道我可以使用正则表达式。但我从来没有使用过。并且发现使用strfind编写数字而不是文本很困难。任何建议或其他方法是受欢迎的。

我曾尝试:

regexp(files.name,'ts.(\d*)1094000.crest.csv','match'); 
+0

我没有MATLAB周围安装所以不能给你确切的代码,但'strfind '在字符串的单元数组上运行,你应该尝试从结构数组中获取文件名到单元数组,然后你可以找到包含你正在查找的文件的索引。如果你决定使用'regex',regex101.com是一个很棒的地方去测试和学习正则表达式。 –

回答

1

我想你想要的正则表达式更像

filenames = {'ts.01100600.crest.csv','ts.01094000.crest.csv'}; 
matches = regexp(filenames, ['ts\.0*' num2str(1094000) '\.crest\.csv']); 
matches = ~cellfun('isempty', matches); 
filenames(matches) 

对于strfind一个解决方案...

预-16B :

match = ~cellfun('isempty', strfind({files.name}, num2str(1094000)),'UniformOutput',true) 
files(match) 

16B +:

match = contains({files.name}, string(1094000)) 
files(match) 

然而,strfind方式,如果可能在意想不到的地方,如[“01000”,“00101”]找10存在,你正在寻找的数字有问题。

如果你的文件名匹配的模式ts.NUMBER.crest.csv,然后在16B +你可以这样做:

str = {files.name}; 
str = extractBetween(str,4,'.'); 
str = strip(str,'left','0'); 
matches = str == string(1094000); 
files(matches) 
+0

你的意思是文件名(匹配)? –

+0

是的,我做过。固定。 – matlabbit

+0

当我在16A中使用时,match = contains({files.name},string(1094000))给了我这个错误:对'double'类型的输入参数未定义函数'string'。 – maximusdooku