extract numbers from a string.

28 views (last 30 days)
Jasmine Zhu
Jasmine Zhu on 12 Sep 2022
Commented: Jasmine Zhu on 13 Sep 2022
str = "sensor_serials": {"H1": "3637", "H2": "3638", "H3": "2787"},
I would like to extract the number 3637, 3638, and 2787 from the above string. How should I do it? Thanks!
  1 Comment
Star Strider
Star Strider on 12 Sep 2022
Something is wrong with that because it throws this error —
str = "sensor_serials": {"H1": "3637", "H2": "3638", "H3": "2787"}
Operator ':' is not supported for operands of type 'string'.

Sign in to comment.

Accepted Answer

Voss
Voss on 12 Sep 2022
str = '"sensor_serials": {"H1": "3637", "H2": "3638", "H3": "2787"}'
str = '"sensor_serials": {"H1": "3637", "H2": "3638", "H3": "2787"}'
numbers = regexp(str,'"(\d+)"','tokens');
numbers = [numbers{:}]
numbers = 1×3 cell array
{'3637'} {'3638'} {'2787'}
numbers = str2double(numbers)
numbers = 1×3
3637 3638 2787
  1 Comment
Jasmine Zhu
Jasmine Zhu on 13 Sep 2022
It worked and thank you!

Sign in to comment.

More Answers (1)

Hiro
Hiro on 12 Sep 2022
You can use pattern:
pat = digitsPattern(4); % Pattern
str = '"sensor_serials": {"H1": "3637", "H2": "3638", "H3": "2787"}'
str = '"sensor_serials": {"H1": "3637", "H2": "3638", "H3": "2787"}'
numbers = extract(str,pat);
string(numbers)
ans = 3×1 string array
"3637" "3638" "2787"
  1 Comment
Jasmine Zhu
Jasmine Zhu on 13 Sep 2022
Thank you for your reply. Unfortunately my matlab doesn't support digitsPattern().

Sign in to comment.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by