I have a log file that gives me a timestamp with two formats:
when time is between [0h,1h[:
11:32.456 - MM:SS.zzz
when time is between [1h,1000h[:
22:45:45.234 - HH:MM:SS.zzz
So i created this regular expression:
(?<hour>\d+)?:?(?<minute>\d+):(?<second>\d+)\.(?<fraction>\d+)
The problem is that if the time is less than one hour ( [0h,1h[ - 11:32.456) the regular expression gives me this:
Hour:1
Minute: 1
seconds: 32
fraction: 456
I need the next result:
Hour: 0
Minute: 11
seconds: 32
fraction: 456
If the time is greater than 1 hour all goes fine.
How can i solve this problem?
Thanks.

 채택된 답변

Star Strider
Star Strider 2019년 7월 24일

0 개 추천

I would just use the hour, minute and second functions.
Note that second will give you the fractions as well.
If you want to separate the fractions:
t1 = datetime('now','Format','dd-MMM-yyyy HH:mm:ss.SSS');
s = second(t1)
fraction = rem(s,1)

댓글 수: 4

Marco Silva
Marco Silva 2019년 7월 24일
Thank you for your advice, however, when my timestamp has the format 11:32.456, I receive the error "Unable to convert '11:32.456' to datetime using the format 'HH:mm:ss.SSS'."
And i cant modify the timestamp because my log file has a several entries
My pleasure.
Use a different input format for those times:
t = datetime('11:32.456', 'InputFormat','mm:ss.SSS');
or add hours:
intime = '11:32.456';
newtime = sprintf('00:%s', intime);
t = datetime(newtime, 'InputFormat','HH:mm:ss.SSS');
You can check to see what the format is with the number lf elements returned by strfind:
clns = strfind(timestr, ':')
where ‘timestr’ is the string you are using to create your datetime object. If there is only one element in the result, add the '00:' using the sprintf call first.
Marco Silva
Marco Silva 2019년 7월 25일
Good trick, thank you!
Star Strider
Star Strider 2019년 7월 25일
My pleasure!

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

추가 답변 (1개)

Stephen23
Stephen23 2019년 7월 25일
편집: Stephen23 2019년 7월 25일

0 개 추천

>> rgx = '(?<H>\d*)(?(1):)(?<M>\d+):(?<S>\d+)\.(?<F>\d+)';
>> regexp('11:32.456',rgx,'names')
ans =
H: ''
M: '11'
S: '32'
F: '456'
>> regexp('22:45:45.234',rgx,'names')
ans =
H: '22'
M: '45'
S: '45'
F: '234'

카테고리

도움말 센터File Exchange에서 Data Type Conversion에 대해 자세히 알아보기

태그

질문:

2019년 7월 24일

댓글:

2019년 7월 25일

Community Treasure Hunt

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

Start Hunting!

Translated by