Extract the number from the file name

5 views (last 30 days)
Songman Liao
Songman Liao on 25 Jan 2018
Answered: Walter Roberson on 25 Jan 2018
Hi, I have 24 files in the folder. 12 of them have names as: "AMS1701-AMsent1.log", "AMS1701-AMsent2.log" to "AMS1701-AMsent12.log". And the rest 12 files have names as: "AMS1701.02-AMsent1.log", "AMS1701.02-AMsent2.log" till "AMS1701.02-AMsent12.log". I want to extract 2 type of number. The first type is the number after AMS1701(whether there is a 02 or not). The second type of number is the one after"AMsent". It can vary from 1 to 12.
Thank you so much for helping me! I would really appreciate if you could show me the procedure.

Answers (2)

the cyclist
the cyclist on 25 Jan 2018
Two commands that are going to be helpful are
  • what -- List MATLAB files in folder
  • regexp -- Match regular expressions
The latter command will allow you to pattern-match for the expressions relevant to what you are searching for. It can be tricky to get used to, so maybe play around a little and then ask for more specific help if you need it.
Or maybe someone here will be a little less lazy than I am being right now, and write out the full solution for you. :-)

Walter Roberson
Walter Roberson on 25 Jan 2018
To detect the .02:
has_02 = isempty( strfind(filename, '.02') å);
You are not clears as to what number you want to extract. I suspect you want the number before the '.log' part:
out = regexp(filename, '\d+(?=\.log)', 'match', 'once')
you could str2double() that if you wanted.

Community Treasure Hunt

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

Start Hunting!