MATLAB: Regexp with a list of keywords

regexp

Hi everbody,
I'm aware regexp is a powerful tool, but I'm a newbie to this and I think my problem is an advanced one:
There is a list of keywords
keywords = {'alpha','basis','colic','druid','even'};
and I want regexp to find in a string all values after these keywords (followed by =).
For example:
str = 'basis=10,alpha=today,druid=none,even=odd,even=even';
gives
'today','10',[],'none',{'odd','even'}
Can you help me?

Best Answer

Using a simple lookaround assertion:
>> keywords = {'alpha','basis','colic','druid','even'};
>> str = 'basis=10,alpha=today,druid=none,even=odd,even=even';
>> fun = @(k)regexp(str,sprintf('(?<=%s=)\\w+',k),'match');
>> out = cellfun(fun,keywords,'uni',0);
>> out{:}
ans =
'today'
ans =
'10'
ans =
{}
ans =
'none'
ans =
'odd' 'even'
Note that each cell of out is itself a cell array, with varying sizes. If you want to unnest the scalar cells, as you indicate in your question, then try this:
>> idx = cellfun(@isscalar,out);
>> out(idx) = [out{idx}]
out =
'today' '10' {} 'none' {1x2 cell}
>> out{:}
ans =
today
ans =
10
ans =
{}
ans =
none
ans =
'odd' 'even'