extract numbers from string in a cell

12 ビュー (過去 30 日間)
S
S 2012 年 5 月 8 日
Hi, I have a cell containing a string such as 'TT21abc.def'. I want to extract just the numbers so I'm left with '21'. Does anyone know how? I tried using sscanf but I was getting errors and think I don't have the right format inputs. Thanks in advance.

採用された回答

Friedrich
Friedrich 2012 年 5 月 8 日
Hi,
you can use regexprep or some ascii value representation comparison to do so, e.g.
a = {'TT21abc.def'};
%ascii value comparison, char(48) = '0' and char(57) = '9'
a{1}(a{1} <= 57 & a{1} >= 48)
%or use regexprep
regexprep(a{1},'\D','')
If you have a cell array with strings, I would use regexprep because it can handle cell arrays of strings as input
b = {'TT21abc.def'
'sdfsdf34435afafsd.,.,3434'}
out = regexprep(b,'\D','')

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2012 年 5 月 8 日
with using function regexp
regexp(a,'\d*','match')
or:
b = {'TT21abc.def'
'sdfsdf34435afafsd.,.,3434'}
out = regexp(b,'\d*','match');
out = cat(2,out{:})

カテゴリ

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