Amir
Amir

Reputation: 11096

Split complex text in MATLAB

I have a string as below:

6121gog211222 412 5511.0 2011-11-29 01:14:46.63231 623 734 I A-BB {"C":true,"A":"KA.NA_CH","T":250,"L":100,"P":false,"LV":"12.0"}

I want to split the string and extract the parts "01:14:46, true, 250, 100 and false".

I tried using strsplit function, but it break the problem into more sub-problems.

Is there an easier way of splitting this text?

Thank you

Upvotes: 0

Views: 74

Answers (1)

Doug Lipinski
Doug Lipinski

Reputation: 644

You'll probably want to use regular expressions to match your substrings. You can read more about regular expressions in MATLAB here

This isn't the prettiest answer but it works. I'm assuming your source string keeps the same format with only one "time" string of format ??:??:?? and data in the format "label":value with fields separated by commas. In that case the following should work.

Define a function getval:

function val=getval(str,label)
%// return the value from the input 'str' associated with the string in 'label'
i1=regexp(str,sprintf('"%s"',label)); %// first index
i2=regexp(str(i1:end),',|}','once'); %// index where field ends
val = str(i1+3+numel(label):i1+i2-2); %// value

You can get your answer using this function as follows:

str = sprintf('6121gog211222 412 5511.0 2011-11-29 01:14:46.63231 623 734 I A-BB\n{"C":true,"A":"KA.NA_CH","T":250,"L":100,"P":false,"LV":"12.0"}');

ii=regexp(str,'..:..:..');
sprintf('%s, %s, %s, %s and %s', ...
          str(ii:ii+7), ...
          getval(str,'C'), ...
          getval(str,'T'), ...
          getval(str,'L'), ...
          getval(str,'P') )

Upvotes: 1

Related Questions