Extract single-digit and double-digit numbers at the same time from a cell array with "regexp"

2 views (last 30 days)
Hi, I am trying to extract the numbers from the following cell array:
a={'1','3','6-10','11-20'};
If I use regexp, the number 10, 11 and 20 are also split:
b=regexp(a,'[0-9]','match');
b{:}
ans = 1×1 cell array
{'1'}
ans = 1×1 cell array
{'3'}
ans = 1×3 cell array
{'6'} {'1'} {'0'}
ans = 1×4 cell array
{'1'} {'1'} {'2'} {'0'}
I would like to have the number 10, 11 and 20 unsplitted. How to do it, maybe still with regexp?
  2 Comments
Sim
Sim on 12 Feb 2024
I found the solution of @Walter Roberson, that I slightly modified (I just removed the option "once" after "match"), but it still holds the minus sign attached to the numbers:
a={'1','3','6-10','11-20'};
b = regexp(a, '(-?\d+(\.\d*)?)|(-?\.\d+)', 'match');
b{:}
ans = 1×1 cell array
{'1'}
ans = 1×1 cell array
{'3'}
ans = 1×2 cell array
{'6'} {'-10'}
ans = 1×2 cell array
{'11'} {'-20'}

Sign in to comment.

Accepted Answer

Les Beckham
Les Beckham on 12 Feb 2024
Edited: Les Beckham on 12 Feb 2024
a={'1','3','6-10','11-20'};
b=regexp(a,'[0-9]+','match'); %<<< add the + to match multiple numeric characters
b{:}
ans = 1×1 cell array
{'1'}
ans = 1×1 cell array
{'3'}
ans = 1×2 cell array
{'6'} {'10'}
ans = 1×2 cell array
{'11'} {'20'}

More Answers (0)

Categories

Find more on Programming 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!