For 'yyyyMMdd_HHmmss' Format:
dateTimeStr1 = '20240109_153535';
pattern1 = '^\d{4}(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})$';
if ~isempty(regexp(dateTimeStr1, pattern1, 'once'))
disp('The string is in the correct "yyyyMMdd_HHmmss" format.');
disp('The string is NOT in the correct "yyyyMMdd_HHmmss" format.');
end
The string is in the correct "yyyyMMdd_HHmmss" format.
For 'yyyy-MM-dd''T''HH:mm:ss.SSS' Format:
dateTimeStr2 = '2023-08-15T06:10:09.89';
pattern2 = '^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{2}$';
if ~isempty(regexp(dateTimeStr2, pattern2, 'once'))
disp('The string is in the correct "yyyy-MM-dd''T''HH:mm:ss.SS" format.');
disp('The string is NOT in the correct "yyyy-MM-dd''T''HH:mm:ss.SS" format.');
end
The string is in the correct "yyyy-MM-dd'T'HH:mm:ss.SS" format.
- The caret (^) at the beginning of the pattern denotes the start of the string.
- \d{4} matches exactly four digits, \d{2} matches exactly two digits, and so on.
- The dollar sign ($) at the end of the pattern denotes the end of the string.
- regexp function is used with the 'once' option to return a match if the string conforms to the pattern.
- For the milliseconds part, I used \d{2} based on your example, but if you need exactly three digits for milliseconds, you should use \d{3} in your pattern instead.
Remember that this method only checks if the string conforms to the specified format. It does not validate whether the date and time themselves are correct (e.g., February 30th would be considered valid by the regex). To perform an actual date-time validation, you would need to try converting the string to a date-time object using datetime and catch any errors that occur for invalid dates.
---------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
Professional Interests
- Technical Services and Consulting
- Embedded Systems | Firmware Developement | Simulations
- Electrical and Electronics Engineering
Feel free to contact me.