Remove text in a string with numbers
83 次查看(过去 30 天)
显示 更早的评论
How can I remove the text part and obtain a vector of just the last numbers?
e.g
Model1__DK1_5450.0
Model2__DK2_6969.0
Model3__DK3_3398.0
0 个评论
采纳的回答
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' }
{'5450'}
{'0' }
or you can use logical indexing:
digitIndexes = txt >= '0' & txt <= '9';
onlyNumbers = txt(digitIndexes)
onlyNumbers =
'1154500'
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
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
2021-4-21
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!