如何根据数字字符串提取文件名?

时间:2016-09-27 01:47:28

标签: regex matlab

我在struct数组中有一个文件名列表,例如:

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'并找到那个名字。

我知道我可以使用Regex来做到这一点。但我以前从未使用过它。并且发现使用strfind编写数字而不是文本很困难。欢迎任何建议或其他方法。

我尝试过:

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

1 个答案:

答案 0 :(得分: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)

但是,如果您要查找的号码存在于意外的位置,例如在[“01000”“00101”]中查找10,则strfind方式可能会出现问题。

如果您的文件名与模式ts.NUMBER.crest.csv匹配,那么在16b +中您可以这样做:

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