Extracting number from a string

2 ビュー (過去 30 日間)
captainmariah
captainmariah 2021 年 3 月 30 日
編集済み: Stephen23 2021 年 3 月 30 日
Hi, I want to extact the number from this string.
res_str ='TotalPower:9,7406E+00Watts'
I used below to find the index of the semi-colon, but how can I get the number from this format?
index = strfind(res_str, ':')-1
theNumber = str2double(res_str(index:21)) % - gives just NAN
Want to find the number positions (the start and end of the number, i.e. pos 12 and 21 in this case) and convert this to a number 9.7406E00
theNumber = (res_str(12:21))
theNumber =
'9,7406E+00'
Many thanks

採用された回答

Stephen23
Stephen23 2021 年 3 月 30 日
str = 'TotalPower:9,7406E+00Watts';
num = sscanf(strrep(str,',','.'),'%*[^:]:%f')
num = 9.7406
  2 件のコメント
captainmariah
captainmariah 2021 年 3 月 30 日
編集済み: captainmariah 2021 年 3 月 30 日
Thank you, I managed to get the number after some fail and trial, but its not as sleek as this code. My attempt.
index1 = strfind(res_str, ':')+1;
index2 = strfind(res_str, 'W')-1;
theNumber = res_str(index1:index2);
totalPower=str2double(theNumber);
What does this part do?
%*[^:]:%f
Stephen23
Stephen23 2021 年 3 月 30 日
編集済み: Stephen23 2021 年 3 月 30 日
"What does this part do?"
That defines the format for extracting data from the string: read the sscanf documentation to know more.
... %*[^:]:%f Three distinct parts of the format string:
... %*[^:] Read and discard all non-colon characters
... : Literal colon character
... %f Read number, including optional exponent

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeString Parsing についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by