2016-09-27 73 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