Can regexp return key / value pairs in a structure?

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 regexpto 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')?

+4
source share
1 answer

You can avoid the for loop by collecting key / value pairs into a single array of cells and then passing its contents as a comma separated list to struct:

args = [lns{:}];
myStruct = struct(args{:});

And the conclusion:

myStruct = 

  struct with fields:

    name: 'John'
     sex: 'M'

regexp textscan , :

strs = textscan(fileID, '%s', 'Delimiter', ':');
myStruct = struct(strs{1}{:});
+5

Source: https://habr.com/ru/post/1686087/


All Articles