How do I convert parentheses of a function into brackets?

Is there a method to convert the parenthesis of the argument of a function into brackets? What I mean is something like:

$$(x+1)\sin\left(y*\sqrt{y\ln{\left(x^2\right)}}\right)\to(x+1)\sin\left[y*\sqrt{y\ln{\left[x^2\right]}}\right]$$ so that it is evaluatable in mathematica.

To get an idea, I've tried:

function = InputString[];
arg = Row[StringDrop[StringDrop[StringCases[function, "(" ~~ __ ~~ ")"], 1], -1]];
temp = ToString[Row[{"(", arg, ")"}]];
temp2 = ToString[Row[{"[", arg, "]"}]];
ToExpression[StringReplace[function, temp -> temp2]]


which works if the user inputs simple functions like $\sin(x\cdot e^x)$ but fails for a slightly more complicated function such as $(x+1)\sin(x\cdot e^x)$. I want to generalize this if possible to the example above.

• Can you provide an example of the input? Not only its rendered form? Unless it is TeX, then make that clear. – Kuba Jan 11 '18 at 19:45
• At least closely related: 132817, Shortly ToExpression["(x+1) sin(y*sqrt(ln(x^2)+ 1))", TraditionalForm], though sqrt needs a little push. – Kuba Jan 11 '18 at 19:47
• Perhaps a duplicate of 76189 – Carl Woll Jan 12 '18 at 7:01
• @Kuba Interpreter[“MathExpression”][function] also works, and probably works best because it also converts “ln” to “Log” and is able to handle lower case nested functions. The only issue is that it needs a internet connection. – DMH16 Jan 12 '18 at 22:38
• @DMH16 yep, is slower and won't work in older versions but may be enough so worth to keep it in mind. – Kuba Jan 12 '18 at 22:42

Not sure what the form of user-input is -- it's typeset TeX output in the question. If raw TeX is the input form, then this works:

ConvertTeXTeXToExpression[
"(x+1)\\sin\\left(y*\\sqrt{y\\ln{\\left(x^2\\right)}}\\right)"]
(*  (1 + x) Sin[y Sqrt[y Log[x^2]]]  *)


Here's a first-order attempt.

We'll check for a head on our round brackets and make sure we have appropriate paren balance. i.e. our pattern will be:

pat =
test : Shortest[head : (WordCharacter ..) ~~ "(" ~~ body__ ~~ ")"] /;
StringCount[test, "("] == StringCount[test, ")"] :>
head <> "[" <> body <> "]"


then we'll embed this in a FixedPoint StringReplace:

FixedPoint[
StringReplace[pat],
"(x+1) sin(y*sqrt(ln(x^2)+ 1))"
]

"(x+1) sin[y*sqrt[ln[x^2]+ 1]]"


This is probably still too fragile an approach, however, so it'll probably require work to make robust. We could also add a SyntaxQ pre-check in there if we want to make sure everything is good before trying to get the square brackets.

I would use a Boxes InputField instead (similar to my answer to the linked question How use TraditionalForm input in InputField?). For example:

DynamicModule[{f=Null},
{