How to read a selected number from a string?
조회 수: 3 (최근 30일)
이전 댓글 표시
Hello,
I have a string:
# Source Interval: 22.99 u (ID: 2)
and I want to read only 22.99 from this string. This number can change in different files as I have multiple files with same string but a different number ranging upto ten thousand. I tried retrieving this number using strread, but everytime I get the error Number of outputs must match the number of unskipped input fields.
Can anyone help?
Thank you
댓글 수: 0
채택된 답변
Jos (10584)
2014년 2월 13일
str = '# Source Interval: 22.99 u (ID: 2)'
v = strread(str,'# Source Interval: %f%*[^\n]')
% The format specifier means the following
% - '%f' - read a floating point number
% - '%*[^\n]' - ignore the rest of the string
추가 답변 (1개)
the cyclist
2014년 2월 13일
편집: the cyclist
2014년 2월 13일
There are multiple ways to do this. Which one is best may depend on how consistent the rest of the text is.
The regexp() command should be able to do everything you need. For example, take a look at this code:
str = '# Source Interval: 22.99 u (ID: 2)';
colonIdx = regexp(str,':');
uIdx = regexp(str,'u');
numRange = colonIdx(1)+2 : uIdx(2)-2;
num = str2num(str(numRange))
Here, I relied on the fact that your numeric string came the first occurrence of a colon and the second occurrence of the letter "u". I used regexp() to find the locations of those characters, and then the relative location of the number.
댓글 수: 2
the cyclist
2014년 2월 13일
I can't be 100% sure what went wrong, without seeing your code, but here is a guess:
"str" is the variable name I gave to your string '# Source Interval: 22.99 u (ID: 2)'. If you decided to name that string something else, then you need to make that replacement everywhere in the code I posted. Otherwise, MATLAB thinks you are trying to call a function named str().
참고 항목
카테고리
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!