S = '(2*3)+Z*14*(3*5)+(7)*(9)-(11)*13'
S = '(2*3)+Z*14*(3*5)+(7)*(9)-(11)*13'
newS = regexprep(S, {'\((\d+)\)\*\((\d+)\)', '\((\d+)\)\*(\d+)', '(\d+)\*\((\d+)\)', '(\d+)\*(\d+)'}, {'${string(times(str2double($1),str2double($2)))}'})
if strcmp(newS, S); break; end
end
newS = '(6)+Z*14*(15)+63-143'
newS = '(6)+Z*210+63-143'
newS = '(6)+Z*210+63-143'
Note that the logic gets more complex if you have operators that are higher priority, such as ^ . For example '2*3^Z' should not have the 2*3 multiplied out.
Also, you could reasonably argue that I did not preserve brackets in some of the cases such as (11)*13 -- it would not be unreasonable to claim that the result of that should be (143) instead of 143 . You could take care of those cases by having four different replacement strings instead of the single replacement I have there.
I did try to unify all of the cases into one case, but stripping off the brackets without using nested regexp or using an auxillary function would have been a bit messy. It would probably be cleanest to use some auxillary functions like
with s_times responsible for stripping off brackets and converting to numeric and doing the multiplication and converting the result to character. It would probably be a good idea to use something like that, and then the cases could probably be reduced to a single case.
0 Comments
Sign in to comment.