Extracting number from a string
754 ビュー (過去 30 日間)
古いコメントを表示
採用された回答
Stephen23
2016 年 12 月 16 日
Here are two very simple methods:
>> str = 'M1';
>> sscanf(str,'M%d')
ans = 1
>> str(2)-'0'
ans = 1
2 件のコメント
その他の回答 (3 件)
Image Analyst
2016 年 12 月 16 日
Here are two ways, depending on if you want the extracted "1" to be a character (string) or a number:
str = 'M1' % First define the string.
str1 = str(2) % Gives a character
dbl1 = str2double(str(2)) % Give a number (double)
Pierre Harouimi
2022 年 11 月 2 日
2 件のコメント
Image Analyst
2022 年 11 月 2 日
編集済み: Image Analyst
2022 年 11 月 2 日
Example:
string = 'abc123def456789ghi'
numbers = str2double(extract(string, digitsPattern))
It would be nice if they made a little wrapper function for that, since it's hard to remember. Something simple like
numbers = extractNumbers(string);
would be easier for most people I think, than having to know about digitsPattern, extract, str2double, and then having to nest them all together.
Stephen23
2022 年 11 月 3 日
編集済み: Stephen23
2022 年 11 月 3 日
"Something simple like... would be easier for most people I think..."
The devil is in the details, because it really depends on what you define as a "number". Some users will want to match fractional digits (which probably means selecting for e.g. comma vs dot vs comma|dot), whereas others will want to match only integers and to treat commas/dots as non-numeric. Ditto exponent notation, NaNs, Infs, other bases, fixed-width numbers, various Unicode minus/plus signs, etc.
So it turns out to be not very simple at all, once the different "number" formats are considered. The user specifying a regular expression or MATLAB pattern is one way to give them that control, by making those choices explicit.
参考
カテゴリ
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!