Using regular expression to read part of the filename

조회 수: 5 (최근 30일)
anton spektorov
anton spektorov 2018년 10월 1일
편집: Stephen23 2018년 10월 2일
Good afternoon,
I am attempting to use a regular expression feature to read part of the file that is generated by the microscope camera.
The file format is x_yyyymmdd_hhmmSSsss where small s is the milisecond and x is the number of the timelapsed photo.
I am trying to convert (truncate) say 5_20180927_161742655 to 20180927_161742 so that I can use this as a timestamp more easily.
Any help would be appreciated. Thank you.

채택된 답변

Stephen23
Stephen23 2018년 10월 2일
편집: Stephen23 2018년 10월 2일
>> str = '5_20180927_161742655';
>> regexp(str,'(?<=_)\d{8}_\d{6}','match','once')
ans = 20180927_161742
Note that the input str can also be a cell array of char vector, or a string array.

추가 답변 (1개)

dpb
dpb 2018년 10월 1일
편집: dpb 2018년 10월 2일
AMMENDED -- dpb
Don't need regular expressions for that purpose, just select the first N-3 characters in the file name...
S=15; % sublength of wanted string (15)
[~,TS]=fileparts(fname); % return the file name w/o path, extension
L=length(TS); % just get the overall length
TS=TS(L-(S+3)+1:L-3); % pick up between file and sss millisec portion
Alternatively, one can
L1=find(fn=='_',1)+1; % location just past first underscore
TS=TS(L1:L-3); % pick up between file and sss
NB: fileparts will return the name as either char array or cellstr depending on input form for fanme going in so may need to dereference a cell string if that is the form.
I'm sure there is a regexp expression that will work but I'm just not adept with its syntax, sorry...
  댓글 수: 2
anton spektorov
anton spektorov 2018년 10월 1일
Thank you dpb!
Unfortunately the number/numbers before the first underscore can go to double and triple digits giving me no easy way to truncate that portion. The milliseconds removal worked perfectly though. Since the entire string should always be yyyymmdd_hhmmss which is 15 spaces counting the underscore is there a way to count 15 from the end once the last 3 characters are removed? Thank you for such a fast reply.
dpb
dpb 2018년 10월 1일
편집: dpb 2018년 10월 2일
Oh, my bad; I didn't notice you'd truncated the first set; makes perfect sense to have done, granted! :)
I updated the ANSWER to handle that situation; just locate the first underscore first.

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

카테고리

Help CenterFile Exchange에서 Workspace Variables and MAT Files에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by