MATLAB: How to open files whose name matches a string from another file name

if statementmatch patternopen filesstring

I have two groups of files that all contain a timestamp in their names. The timestamps are identical between file groups. I want to match the files from Group 1 with their counterpart in Group 2, but there are more files in Group 1 than in Group 2. How do I only open files from Group 1 that match a timestamp in Group 2? The timestamp is only part of the filename.
Ex. CAL_LID_2011-11-01T00-47-43ZN.nc
The '2011-11-01T00-47-43' is the timestamp that needs to be matched to a file in Group 2. I've tried to write an if statement to open the files, but I'm stuck. Any help is appreciated! Thanks!

Best Answer

Assuming timestamps are all of the same form, you can find them with regexp:
%filesgroup1: a cell array of string representing file names from group 1
tstamps1 = regexp(filesgroup1, '\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}', 'match', 'once');
You can do the exact same thing for group 2:
filesgroup2: a cell array of string representing file names from group 2
tstamps2 = regexp(filesgroup1, '\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}', 'match', 'once');
You can then check which timestamps from group 2 are in group 1 with ismember:
isingroup1 = ismember(tstamps2, tstamps1);
Finally, you use the logical array returned by ismember to filter your group2 filenames:
files2match1 = filesgroup2(isingroup1);
Note: the regexp matches 4 digits, followed by '-', followed by 2 digits, followed by '-', followed by 2 digits, followed by 'T', followed by 2 digits, followed by '-', followed by 2 digits, followed by '-', followed by 2 digits.