Read only numbers from string

17 ビュー (過去 30 日間)
SJ Won
SJ Won 2019 年 7 月 5 日
コメント済み: SJ Won 2019 年 7 月 8 日
Given a string, how to read only the numbers? I am trying to sum them up afterward.
This was my solution:
splitted = strsplit(str)
total = 0;
array = [];
for i=1:numel(splitted)
if ~isnan(str2double(splitted{i}))
array = [array " " splitted{i}]
end
end
total = nansum(str2double(array))
However, this is only assuming the numbers are not attached to any characters. Strings like '42hi' would not be counted.
I then thought about something like this:
multiple_digit = [];
single_digit = [];
k=1;
for ii=1:numel(str)
if isa(str2num(str(ii)), 'double')
if ~isa(str2num(str(ii+1)), 'double') %if next character isn't a number, then puts that number in
single_digit(k) = str2num(str(ii))
end
end
end
I am checking each individual characters in the string to see if it is a number. If it is, then I check to see if the next character is also a number so that I can take a string like '100' as 100, not 1. However, this seems very complicated, as I have to control whether I am going out of the array index or not.
  2 件のコメント
Stephen23
Stephen23 2019 年 7 月 5 日
編集済み: Stephen23 2019 年 7 月 5 日
"However, this is only assuming the numbers are not attached to any characters. Strings like '42hi' would not be counted."
What does this mean? Do you want to match that 42 or not?
Your question is missing the most important information of all: an actual specification or example of what the string and number substrings are like. It is very difficult to write code to parse strings given no information about exactly what is in the string, how the numbers are to be identified, etc.
"However, this seems very complicated..."
It is very complicated. Read this:
SJ Won
SJ Won 2019 年 7 月 8 日
I was referring to how my code would encode strings like 42hi as 4 and 2, when I want the 42 itself.

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

採用された回答

Stephen23
Stephen23 2019 年 7 月 5 日
編集済み: Stephen23 2019 年 7 月 5 日
"Given a string, how to read only the numbers?"
That really depends on what you define as being a "numberˇ: which of these are "numbers" according to your definition?:
  • 1
  • -1
  • +1
  • 1.0
  • 1e-2
  • NaN
  • Inf
  • 1+2i
  • i
  • e
  • pi
  • etc. etc.
If you are only interested in matching integers, then this should get you started:
>> str = '12 3 4';
>> sum(str2double(regexp(str,'\d+','match')))
ans = 19
  1 件のコメント
SJ Won
SJ Won 2019 年 7 月 8 日
Sorry, I never considered the possibility of other expressions that could represent numbers, so it was quite interesting to see how this question I posed could expand further to other forms. I was solely referring to integers, such as extracting out 42 as 42, not as 4 or 2, and your comment resolves my question. Thank you.

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

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