Effacer les filtres
Effacer les filtres

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

5 vues (au cours des 30 derniers jours)
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 commentaires
Sim
Sim le 12 Fév 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 le 12 Fév 2024
Déplacé(e) : Stephen23 le 12 Fév 2024
Great answers both @Stephen23 and @Les Beckham!! I would accept both obviously!

Connectez-vous pour commenter.

Réponse acceptée

Les Beckham
Les Beckham le 12 Fév 2024
Modifié(e) : Les Beckham le 12 Fév 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'}

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by