Read only numbers from string

조회 수: 24 (최근 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 CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by