How do I extract number from file name?

41 ビュー (過去 30 日間)
Emmanuel
Emmanuel 2017 年 3 月 2 日
編集済み: Stephen23 2017 年 3 月 2 日
My file names are like 1443242345.88.png,1232342.45.png. I want these numbers of the file name and extract them as integers like 1443242345.88, 1232342.45 and use them for mathematical operations.
How do I do it with regexp or any other method?
  1 件のコメント
Stephen23
Stephen23 2017 年 3 月 2 日
1443242345.88 is not an integer.

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

採用された回答

Emmanuel
Emmanuel 2017 年 3 月 2 日
So, this works: if A is 1443242345.88.png
A = A(1:end-4)
At = str2num(A)
gives numeric value of A which is 1443242345.88
  1 件のコメント
Stephen23
Stephen23 2017 年 3 月 2 日
編集済み: Stephen23 2017 年 3 月 2 日
It would be better to use str2double, because this avoids the slow eval inside str2num and gives predictable output with non-number input strings:
At = str2double(A)
and also your code does not take into account the fact that file extensions are not always the same length, e.g. .m, .jpeg, etc. A much more robust solution is to use fileparts, which will always split this correctly:
[P,N,E] = fileparts(A);
V = str2double(N);
You also might like to consider Guillaume's very nice answer with regexp.

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

その他の回答 (1 件)

Guillaume
Guillaume 2017 年 3 月 2 日
編集済み: Guillaume 2017 年 3 月 2 日
An integer is a number with no fractional part so 1443242345.88 is not an integer.
numbers = str2double(regexp(filenames, '\d+\.\d+', 'match', 'once'))
will extract the numbers as double and assumes that all numbers have a dot in them
tokens = regexp(filenames, '(\d+)\.(\d+)', 'tokens', 'once');
numbers = str2double(vertcat(tokens{:}))
will extract the numbers on each side of the dots as a two column matrix of integers.
Note: and either will work will a cell array of filenames, so you can do the conversion in one go for ALL your files unlike your solution which you accepted when I was writing mine.
Note 2: and because I use str2double instead of str2num, the solution doesn't risk executing arbitrary code.

カテゴリ

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