Say I have an array of characters with key / value pairs:
ch = sprintf('name: John\nsex: M\n')
ch =
'name: John
sex: M
'
This is just a sample. The actual data is in the file and has many pairs. I can use regexp
to get tokens and then use a for loop to assign them to a structure:
lns = regexp(ch, '(\w*):\s(.*?)\n', 'tokens');
for i = 1:numel(lns)
myStruct.(lns{i}{1}) = lns{i}{2};
end
myStruct =
struct with fields:
name: 'John'
sex: 'M'
Is there an easier way to achieve this, for example using regexp(ch, expr, 'names')
?
source
share