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

8 次查看(过去 30 天)
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