Borrar filtros
Borrar filtros

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

6 visualizaciones (últimos 30 días)
MDias
MDias el 26 de En. de 2021
Comentada: MDias el 26 de En. de 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?

Respuesta aceptada

Jan
Jan el 26 de En. de 2021
Editada: Jan el 26 de En. de 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.

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by