Using regexp to extract day number from long string
조회 수: 1 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
답변 (1개)
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
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 Center 및 File Exchange에서 File Operations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!