Problem using sscanf in picking out numbers from string.

57 ビュー (過去 30 日間)
Nicki
Nicki 2013 年 12 月 2 日
コメント済み: Nicki 2023 年 10 月 28 日
So, I have the string:
str1=D993920x2ExlsSuited20.xls
And I want to pick out the numbers in the string, to give me a vector like
res=[993920 2 20]
Allowing me to pick up the last number for use in naming a txt document.
However, I cannot get sscanf to give me this.
I tried using.
res = sscanf(str1, ['%d'])
Shouldn't this give me the numbers in the string at least? All I get is a space sign...
All help on this would be greatly appreciated.
Best regards, Nicki Eriksen.

採用された回答

Laura Proctor
Laura Proctor 2013 年 12 月 2 日
The following code should give you results close to what you want:
res = sscanf(str1,'%*[^0123456789]%d')
The idea is that sscanf will try to match all the strings specified, and if it doesn't find a match, then it returns what is found. So, when you use '%d', since the first character in the string is a letter and not a number, it doesn't find a match, and returns nothing.
In the code above, the first element is looking for anything that doesn't match the numbers 0-9. The carat in the beginning indicates a non-match. The asterisk indicates that you don't want to save that information in the output. So, it looks for non-numbers then numbers alternating until the end of the string and only saves the numbers. The documentation for textscan explains it better.
  3 件のコメント
Stephen23
Stephen23 2023 年 10 月 28 日
"...the carat, *, inverts this, so that I am looking for everything not in here. Why is the ^ there?"
You have mixed up the names of the symbols. The caret ^ is used to invert the match inside the square brackets. The asterisk * excludes that data from the output.
Nicki
Nicki 2023 年 10 月 28 日
Yes. I realize that now, thank you for clearing it up though.

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

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2023 年 10 月 27 日
str1 = 'D993920x2ExlsSuited20.xls';
%method 1
res = str2double(regexp(str1, '\d+', 'match'))
res = 1×3
993920 2 20
%method 2
res = double(extract(string(str1), digitsPattern))
res = 3×1
993920 2 20
  1 件のコメント
Nicki
Nicki 2023 年 10 月 28 日
Hi. Thanks for the solution. My question is 10 years old, but his was the exact solution I was looking for. Can't remember what I ended up using though.

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

カテゴリ

Help Center および File ExchangeLarge Files and Big Data についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by