Remove text in a string with numbers

84 ビュー (過去 30 日間)
Chiara Scarpellini
Chiara Scarpellini 2021 年 4 月 20 日
コメント済み: Image Analyst 2021 年 4 月 21 日
How can I remove the text part and obtain a vector of just the last numbers?


Image Analyst
Image Analyst 2021 年 4 月 20 日
編集済み: Image Analyst 2021 年 4 月 20 日
You need to use digitsPattern:
txt = 'Model1__DK1_5450.0 '
pat = digitsPattern;
onlyNumbers = extract(txt, pat)
onlyNumbers =
4×1 cell array
{'1' }
{'1' }
{'0' }
or you can use logical indexing:
digitIndexes = txt >= '0' & txt <= '9';
onlyNumbers = txt(digitIndexes)
onlyNumbers =
Or you can do fancier parsing if you just want certain numbers. Such as:
setOf4Digits = onlyNumbers(3:end-1); % Get only the 5450
Do you want the underlines, dots, and minus signs included?
  3 件のコメント
Image Analyst
Image Analyst 2021 年 4 月 20 日
Well, you can either use indexing like this:
txt = 'Model1__DK1_5450.0 '
lastUnderlineIndex = find(txt == '_', 1, 'last');
% Extract from one past the last underline onwards.
onlyNumbers = strtrim(txt(lastUnderlineIndex + 1: end)) % strtrim gets rid of trailing space.
or you can use the regexp() method like Star shows. Your choice - either works.
In your original post, you posted strings with a trailing space. If you don't have that, you can omit the call to strtrim().
Image Analyst
Image Analyst 2021 年 4 月 21 日
@Chiara Scarpellini, just checking back. You did not accept either answer. Are you still there?


その他の回答 (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