Filter löschen
Filter löschen

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

6 Ansichten (letzte 30 Tage)
MDias
MDias am 26 Jan. 2021
Kommentiert: MDias am 26 Jan. 2021
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?

Akzeptierte Antwort

Jan
Jan am 26 Jan. 2021
Bearbeitet: Jan am 26 Jan. 2021
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.

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by