regex - Extracting data between curly brackets in text file in MATLAB -
i have text file has multiple lines , hierarchies this:
... ... ... hierarchy { { b { name "b1" type virtual } c { name "c1" parent "b1" } d { name "d1" type virtual } } { b { name "b2" type virtual } c { name "c2" parent "b1" } d { name "d2" type virtual } } } ... ...
i looking @ extracting text "a {" till end of quotes matching "a" in matlab. content inside "a" vary in number of elements (there more name , contains fields). there way extract "a" , possibly fields cell array?
any appreciated!
i guess want code work number of object , name.
i'd recommend store objects in structs (but change code full cell array if wanted), , guess want code work n objects in pattern you've specified. regexp , cell arrays wouldn't best thing use here, recursion would. but, code below should work example , number of objects. comments should explain what's going on.
% open file fid = fopen('input.txt'); % line file tline = fgetl(fid); % assign tokens starttoken = '{'; endtoken = '}'; % initialise counters bracketcount = 0; objectcount = 0; % initialise root object store parsed file data = {}; % initialise children cell array store names of objects children = {}; % while not finished file while ischar(tline) % check { indexstart = regexp(tline, starttoken); % check } indexend = regexp(tline, endtoken); % if { found if ~isempty(indexstart) % increment bracket counter bracketcount = bracketcount + 1; % extract item name item = strtrim(tline(1:indexstart-1)); % if root if bracketcount == 1 % increase object count objectcount = objectcount + 1; % initialise object in cell array data{objectcount}.name = item; % if not root object (e.g. a) else % initialise item field in object struct data{objectcount}.(item) = []; end % keep track of item name children{bracketcount} = item; % optional display line disp(['start: ' tline]) % if } found elseif ~isempty(indexend) % decrement bracket counter bracketcount = bracketcount - 1; % optional display line disp(['end: ' tline]) % no brackets name value pair assumed else % split line 2 -> {name, value} namevalue = strsplit(strtrim(tline)); % if line isnt empty , there 2 items if ~isempty(namevalue) && numel(namevalue) == 2 % assign value (namevalue{2}) field (namevalue{1}) % of current child (children{bracketcount}) of current % object (doc{objectcount}) data{objectcount}.(children{bracketcount}).(namevalue{1}) = namevalue{2}; % optional display line disp(['name:' namevalue{1} ', value:' namevalue{2}]) end end % next line file tline = fgetl(fid); end % close file fclose(fid);
Comments
Post a Comment