Using regexp to extract day number from long string

조회 수: 1 (최근 30일)
Nicolas Gomez
Nicolas Gomez 2020년 9월 14일
편집: the cyclist 2020년 9월 15일
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

답변 (1개)

the cyclist
the cyclist 2020년 9월 15일
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
Nicolas Gomez
Nicolas Gomez 2020년 9월 15일
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 2020년 9월 15일
편집: the cyclist 2020년 9월 15일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by