Using regexp to extract day number from long string

1 view (last 30 days)
If I have a date as part of a path to a file, for example: 'folder\files and things\1996\other folder\ 6 <month>\ more files.txt', I want to be able to extract the number value (6) representing the day of any month using regexp and assuming the the file path may have other number within it. Any help is appreciated. Thanks

Answers (1)

the cyclist
the cyclist on 15 Sep 2020
Is the directory depth reliably constant? If so, then
% Input data
str = 'folder\files and things\1996\other folder\ 6 <month>\ more files.txt';
% Find the directory separators
slashLocations = regexp(str,'\');
% Extract the substring at the correct directory depth
substr = str(slashLocations(4)+1:slashLocations(5)-1);
% Extract the day of the month
dayOfMonth = regexp(substr,'\d*','match');
  2 Comments
Nicolas Gomez
Nicolas Gomez on 15 Sep 2020
No the depth will not be constant. I basically just want a line of code that will check the string and if it finds one of the twelve months, to look to see if there is a number to the left and if there is to save it in a variable.
the cyclist
the cyclist on 15 Sep 2020
Edited: the cyclist on 15 Sep 2020
Understood. Is the directory with the month is always the last subdirectory before the filename, or could there be further subdirectories below it? The main reason I ask is that code that relies on this might be much simpler than needing to code in the different month names, do multiple regexp checks, etc.
But, if that is not the case, then ...
Are the month names the standard 3-letter abbreviations, or the full month name?
Can it be assumed that those month names (or abbreviations) do not appear elsewhere in the path? For example, do we need to worry about something like
str = 'folder\files and things\1996\December billing files\ 6 December\ more files.txt';
or
str = 'folder\files and things\1996\Decadent cake recipes\ 6 Dec\ more files.txt';
These sorts of regexp tasks always come down to the details of what can be assumed about the string you are looking for, compared to all the stuff you do not want to find.

Sign in to comment.

Categories

Find more on File Operations in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!