kbc
kbc

Reputation: 61

Extracting name-value key pairs from a character array

I have name-value pairs in a character array:

a = '{A=true, up=false, left=false, B=false, select=false, right=false, down=false, start=false}'

Note that the accolades { are all included in array, and size is 1x92.

How can I extract all key value pairs into separate accessible values?

Upvotes: 0

Views: 147

Answers (2)

Paolo
Paolo

Reputation: 26211

A more compact solution, no loop required:

s = regexp(a,'[{=, }]','split');
s(strcmp(s,{''})) = [];
name_val = [s(1:2:end) ; s(2:2:end)].'

name_val =

8×2 cell array

{'A'     }    {'true' }
{'up'    }    {'false'}
{'left'  }    {'false'}
{'B'     }    {'false'}
{'select'}    {'false'}
{'right' }    {'false'}
{'down'  }    {'false'}
{'start' }    {'false'}

Upvotes: 3

Adriaan
Adriaan

Reputation: 18187

strsplit() using a custom delimiter is your friend:

a = '{A=true, up=false, left=false, B=false, select=false, right=false, down=false, start=false}';
% Get rid of leading and trailing characters, split on pairs
tmp = strsplit(a(2:end-1),',');
name_val = cell(numel(tmp,2));  % store in 2 column cell
for ii = 1:numel(tmp)
    tmp2 = strsplit(tmp{ii}, '=');  % Split name-value pair on =
    name_val{ii,1} = strtrim(tmp2{1});  % name
    name_val{ii,2} = strtrim(tmp2{2});  % value
end

name_val =

  8×2 cell array

    {'A'     }    {'true' }
    {'up'    }    {'false'}
    {'left'  }    {'false'}
    {'B'     }    {'false'}
    {'select'}    {'false'}
    {'right' }    {'false'}
    {'down'  }    {'false'}
    {'start' }    {'false'}

This will make you end up with a cell array of n rows, as many as you have key-value pairs, and 2 columns: key in the first, value in the second. I opted for a cell, rather than a struct, since your key names have different length, and cells allow for flexibility in the second column if you mix logical, numeric, and what have you not as keys.

I used strtrim() to get rid of any leading/trailing white space.

Upvotes: 3

Related Questions