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

4 visualizaciones (últimos 30 días)
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 comentarios
Sim
Sim el 12 de Feb. de 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'}
Sim
Sim el 12 de Feb. de 2024
Movida: Stephen23 el 12 de Feb. de 2024
Great answers both @Stephen23 and @Les Beckham!! I would accept both obviously!

Iniciar sesión para comentar.

Respuesta aceptada

Les Beckham
Les Beckham el 12 de Feb. de 2024
Editada: Les Beckham el 12 de Feb. de 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'}

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by