MATLAB Answers

Problem using sscanf in picking out numbers from string.

14 views (last 30 days)
Nicki on 2 Dec 2013
Commented: Nicki on 2 Dec 2013
So, I have the string:
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.

Accepted Answer

Laura Proctor
Laura Proctor on 2 Dec 2013
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.
  1 Comment
Nicki on 2 Dec 2013
Yes, thank you, that helped me. I would suggest more, or maybe more diverse, examples in the documentation. I will look in to the documentation for textscan. Thank you for your help.
One (two actually) final question(s), to make sure I got it right,
%[ ] The symbols in these mark what I am looking for, the carat, *, inverts this, so that I am looking for everything not in here.
Why is the ^ there?

Sign in to comment.

More Answers (0)


Community Treasure Hunt

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

Start Hunting!