フィルターのクリア

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.
  1 件のコメント
MDias
MDias 2021 年 1 月 26 日
Thanks Jan!
sscanf is what I need.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by