Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple capture groups in MATLAB

Tags:

regex

matlab

I have a string that either has a number or the letter a, possibly followed byr or l.

In MATLAB the following regexp returns as

>> regexp('10r', '([0-9]*|a)(l|r)*', 'match')
ans = 
    '10r'

I would expect 10 and r separately, because I have two capture groups. Is there a way to get a cell array with both returned independently? I can't see it in the documentation.

like image 248
RazerM Avatar asked Sep 15 '25 15:09

RazerM


1 Answers

You want 'tokens' instead of 'match'

>> toks = regexp('10r', '([0-9]*|a)(l|r)*', 'tokens');
>> toks{1}
ans = 
    '10'    'r'

Or if you want to get fancy, name the tokens and get a struct array:

>> toks = regexp('10r', '(?<number>[0-9]*|a)(?<letter>l|r)*', 'names');
>> toks
toks = 
    number: '10'
    letter: 'r'
like image 121
Peter Avatar answered Sep 17 '25 08:09

Peter