I am looking at a file generated by another CAS. I'd like to convert it to Mathematica syntax.
Only issue is how to convert exp(....)
to Exp[....]
. I am using StringReplace
with pattern to do the replacement but it is not catching all possible cases. I am not good at regular expressions in Mathematica.
Here are 5 simple input examples to test with
ClearAll[z]
str1 = "exp(x)^2";
str2 = "exp((x+2))";
str3 = "exp( (x+2) * exp(exp(x)+2) )";
str4 = "(4*x)/exp((x-(2/5))/((3/(exp(x)+5))*4+(x-(2-x))*x))+4"
str5="(20*x^4+(-30)*x^3+12*x^2+4*x)*exp(x)^2+(200*x^4+(-300)*x^3+300*x^2+(-236)*x)*exp(x)+(500*x^4+(-750)*x^3+1500*x^2+(-1400)*x+720)"
These should become
str1 = "Exp[x]^2";
str2 = "Exp[(x+2)]";
str3 = "Exp[ (x+2) * Exp[Exp[x]+2] ]";
str4 = "(4*x)/Exp[(x-(2/5))/((3/(Exp[x]+5))*4+(x-(2-x))*x)]+4"
str5 = "(20*x^4+(-30)*x^3+12*x^2+4*x)*Exp[x]^2+(200*x^4+(-300)*x^3+300*x^2+(-236)*x)*Exp[x]+(500*x^4+(-750)*x^3+1500*x^2+(-1400)*x+720)"
This is what I tried among many other things
StringReplace[str, "exp(" ~~ z__ ~~ ")" :> "Exp[" ~~ z ~~ "]"]
Only the first and second worked.
The third one, it did not change any of the internal ones. it failed on str4
and str5
also.
Any suggestions how to do this conversion all in one command? Either using string patterns or regular expression in Mathematica.
I am using version 12.3.1
StringReplace
is indeed a wolframized version of extended regular expressions. In the case of nested parentheses it's noteworthy that extended regular expressions are simply not expressive enough construct to handle arbitrary counting and matching of nested parentheses, which is required here (unless you work around it with the@
trick). $\endgroup$