How to separate a portion of filename from a file

11 次查看(过去 30 天)
How to separate a portion of filename from a file like I have the file 'scrubbed.MOD_D3_AOD_550.20020112.nc' I just want to extract the '20020112' part

采纳的回答

Adam Danz
Adam Danz 2019-9-8
编辑:Adam Danz 2019-9-8
[~, fname] = fileparts('scrubbed.MOD_D3_AOD_550.20020112.nc');
[~,tok] = regexp(fname,'.(\d+)$','match','tokens');
str = tok{1}{1};
  4 个评论
Adam Danz
Adam Danz 2019-9-8
编辑:Adam Danz 2019-9-8
Glad I could help. The other answers here reminded me to make clear the assumption in my answer that the string of interest is always at the end of the filename (ignoring the final file extension) and is preceeded by a decimal point.

请先登录,再进行评论。

更多回答(3 个)

Stephen23
Stephen23 2019-9-8
Simpler:
>> str = 'scrubbed.MOD_D3_AOD_550.20020112.nc';
>> out = regexp(str,'\d{8}','match','once')
out = 20020112
  2 个评论
Adam Danz
Adam Danz 2019-9-8
It is simpler and assumes that the string of interest will always have 8 digits and that will be the only sub-string with 8 digits.

请先登录,再进行评论。


Image Analyst
Image Analyst 2019-9-8
Try strsplit():
parts = strsplit('scrubbed.MOD_D3_AOD_550.20020112.nc', '.') % Separate in between dots.
yourNumber = parts{end-1} % Take the next to the last one.
  2 个评论
Adam Danz
Adam Danz 2019-9-8
编辑:Adam Danz 2019-9-8
This is also simpler than my answer if the assumptions are true that the string of interest is the 2nd to last segment surrounded by decimal points.

请先登录,再进行评论。


madhan ravi
madhan ravi 2019-9-8
regexp('scrubbed.MOD_D3_AOD_550.20020112.nc',...
'\d*(?=\.nc)','match','once')

类别

Help CenterFile Exchange 中查找有关 String Parsing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by