Search code examples
stringmatlabsimplification

Simplify a string with MATLAB script


I have a string format which looks like this (this is not always 'A' and 'number' before '_' and numbers) :

Eq = 'A_number_1+((A_number_2+A_number_3)&(A_number_+A_number_5))+A_number_6';

How can i simplify the string like this (with a script) :

Eq = 'A_number_(1+((2+3)&(4+5))+6)'

For me the simplest way would be to delete all string before a '_' except the first one but i don't know how to do it in a script.

Edit : I tried this

Fq = regexprep(Eq, '^([A-Z]+_)(.*)', '$1\(${strrep($2,$1,'''')}\)');

But it remove only 'A_' and keep 'number' iterations.

Thank you in advance for your help !


Solution

  • Regexp could do the job but i don't understand how to use it so i did like this :

    A = 'A_number_1+((A_number_2+A_number_3)&(A_number_+A_number_5))+A_number_6';
    CR_string = '';
    for i=1:length(A)
        if A(i) == '('
        else
            if str2double(A(i)) == 1
                break;
            else
                CR_string = strcat(CR_string, A(i));
            end
        end
    end
    A = erase(A, CR_string);
    A = strcat(CR_string, '(', A, ')');
    disp(A);
    

    Edit with regexp :

    NewStr = regexprep(Str, '^(\w+?)(\d+\W.*)', '$1\(${strrep($2,$1,'''')}\)');