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

4 次查看(过去 30 天)
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 个评论
Sim
Sim 2024-2-12
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'}

请先登录,再进行评论。

采纳的回答

Les Beckham
Les Beckham 2024-2-12
编辑:Les Beckham 2024-2-12
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'}

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by