This is a string that displays as formatted x^2:

 "\!\(x \^2 \)"

If I left off the closing parenthesis for example:

 "\!\(x \^2 "

Upon evaluation the front end shows a red bracket and a useless message which is simply "The String"

Question is how can we programmatically test for a valid string? Check doesn't seem to catch it. I'm supposing actually parsing the full string syntax would get pretty involved.

This came up while thinking about this question How to recover "pretty" format after split? by the way.

Edit: example illustrating a valid string where SyntaxQ will report False

 "\!\(  x \^2 =  \)"

enter image description here

  • $\begingroup$ Have a look at SyntaxQ. $\endgroup$ – Leonid Shifrin Dec 28 '15 at 20:57
  • $\begingroup$ SyntaxQ indeed catches the error. Its not a fully general solution however because it will false negative on a properly formatted expression that is not itself a syntactically correct expression. $\endgroup$ – george2079 Dec 28 '15 at 21:06
  • $\begingroup$ It is not clear then, what is your definition of a valid string. I would not call the string in your last example a valid string, because it does not result in a valid Mathematica expression when parsed. $\endgroup$ – Leonid Shifrin Dec 28 '15 at 21:35
  • $\begingroup$ @LeonidShifrin you might for example use box formatting to construct a plot label that doesn't need to be a valid mathematica expression. In this context I'd consider valid anything that the front end displays without red flagging the cell. $\endgroup$ – george2079 Dec 28 '15 at 21:46
  • $\begingroup$ But your last example does lead to red-flagging the cell: it is just x^2 = , which isn't the correct syntax. So at least you need to change it to something else, to illustrate your point. It isn't clear to me, for example, that there exists a single example of "anything that the front end displays without red flagging the cell", on which SyntaxQ gives False. $\endgroup$ – Leonid Shifrin Dec 28 '15 at 22:04

One approach .. If you do ToString on an "invalid" formatted string it just returns itself, so we can do this:

validstring[s_String] := 
 Nand[StringMatchQ[s, ___ ~~ "\!\(" ~~ ___](*false for plain string*),
      ToString[s] === s (* false for valid string containing formatting*)]
validstring /@ { 
   "\!\(  x \^2  \)",
   "1 + \!\(  x \^2  \)",
   "\!\( [ x \^2 ] \)",
   "\!\(  x \^2  " ,

{True, True, True, False, True, True}

dropping the flagged item, the rest display fine (even though one is obviously not a valid mathematica expression )

enter image description here


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.