简体   繁体   中英

How can I extract a file name based on number string?

I have a list of filenames in a struct array, example:

4x1 struct array with fields:

    name
    date
    bytes
    isdir
    datenum

where files.name

ans =

ts.01094000.crest.csv


ans =

ts.01100600.crest.csv

etc.

I have another list of numbers (say, 1094000). And I want to find the corresponding file name from the struct.

Please note, that 1094000 doesn't have preceding 0. Often there might be other numbers. So I want to search for '1094000' and find that name.

I know I can do it using Regex. But I have never used that before. And finding it difficult to write for numbers instead of text using strfind. Any suggestion or another method is welcome.

What I have tried:

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

I think the regular expression you'd want is more like

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

For a solution with strfind...

Pre-16b:

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

16b+:

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

However, the strfind way might have issues if the number you are looking for exists in unexpected places such as looking for 10 in ["01000" "00101"].

If your filenames match the pattern ts.NUMBER.crest.csv, then in 16b+ you could do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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