7

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

george2079
  • 38,913
  • 1
  • 43
  • 110
  • Have a look at SyntaxQ. – Leonid Shifrin Dec 28 '15 at 20:57
  • 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. – george2079 Dec 28 '15 at 21:06
  • 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. – Leonid Shifrin Dec 28 '15 at 21:35
  • @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. – george2079 Dec 28 '15 at 21:46
  • 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. – Leonid Shifrin Dec 28 '15 at 22:04
  • I don't get an error - I added a screengrab. (I must admit this is a pretty academic exercise..in most cases the frond end error is all you need.) – george2079 Dec 28 '15 at 22:14
  • Ok, I understand now. Indeed, you are right, FE barks on badly escaped strings but is Ok with properly escaped strings even when they don't represent the correct syntax. – Leonid Shifrin Dec 29 '15 at 13:48

1 Answers1

7

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  " ,
   "\!\(x\)",
   "x"}

{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

george2079
  • 38,913
  • 1
  • 43
  • 110