필터 지우기
필터 지우기

Get only the digits in the first 2 characters of a string

조회 수: 6 (최근 30일)
MDias
MDias 2021년 1월 26일
댓글: MDias 2021년 1월 26일
Hello,
I'm trying to find the numbers of a list of file names. Each file name starts with a variable numbers between 1 and 15:
filename1 = '13_data_rec_233';
filename2 = '1_data_rec_124';
I need to store the number of each file (digits before the underscore) for later use. In this case I can't cimply get the first two chracters as for filename2 it would get '1_'
Any suggestion on how to proceed?

채택된 답변

Jan
Jan 2021년 1월 26일
편집: Jan 2021년 1월 26일
filename1 = '13_data_rec_233';
filename2 = '1_data_rec_124';
num1 = sscanf(filename1, '%d', 1)
num2 = sscanf(filename2, '%d', 1)
Or do you want the number as char vector?
num1 = strtok(filename1, '_')
num2 = strtok(filename2, '_')
If there is no separator as "_" in your case, this can help:
filename1 = '13data_rec_233'; % Could be '13value_rec_233' also
filename2 = '1data_rec_124'; % Could be '1value_rec_124' also
num1 = FirstNumber(filename1)
num2 = FirstNumber(filename2)
function T = FirstNumber(S)
alpha = ~strprop(S, 'digit');
T = S(1:find(alpha, 1));
end
If the numerical value is needed, use sscanf() as above.
Of course regexp is working also, but its bigger power leads to slower run times.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by