I'm doing this:

enter image description here

And get this:

enter image description here

But what I wanted is:

enter image description here

How can I get the desired output? Is there a way to recover the format from the cryptic output?

Note: my "real" list is way longer than just two terms and I want to keep the "pretty" format in order to show the output.

  • 1
    $\begingroup$ This isn't general enough but maybe good enough for you so: ToString[#, StandardForm] & /@ ToExpression[ "{" <> # <> "}"] &@myString $\endgroup$
    – Kuba
    Dec 28, 2015 at 20:00
  • $\begingroup$ If you do FullForm on your string you will see the underlying plain text string contains several commas. StringSplit splits on those and so the result would be pretty hard to undo. $\endgroup$
    – george2079
    Dec 28, 2015 at 20:08
  • 2
    $\begingroup$ Please post properly-formatted, copy-and-paste-able Mathematica code rather than screenshots of your code. It's nice to be able to just copy and paste code into our own copies of Mathematica instead of re-typing expressions the OP has already written. $\endgroup$
    – march
    Dec 28, 2015 at 20:12
  • $\begingroup$ @george2079, OK, but how can I get the result? Maybe with another approach $\endgroup$ Dec 28, 2015 at 20:12
  • 1
    $\begingroup$ @march If you can show me how to show X_u with the pretty format by just copying the code I'll be glad to post a copy-paste version. $\endgroup$ Dec 28, 2015 at 20:55

2 Answers 2


This might work for you. The idea is to create a PatternTest function which only returns True outside of box structures.

mysplit[s_String, c_String] := Module[{f, i = 0},
  f["\("] := i++;
  f["\)"] := i--;
  f[c] := i == 0;
  StringSplit[s, _?f]]

enter image description here


a bit of an overkill answer:

start with a somewhat more involved example. The string is keyed in using control-_ for subscripts etc.

enter image description here

{"Y", "!(*SubscriptBox[(X)", " (u)])", \ "!(*SubscriptBox[(X)", " (p)])", "X", \ "!(*TagBox[SubsuperscriptBox[\"x\"", " \"0\"", " \"n\"]", " DisplayForm])", "p"}

this is a mess because StringSplit has operated on all the commas embedded in the format code.

so.. reassemble by joining parts until they are valid strings. (see https://mathematica.stackexchange.com/a/102969/2079 )

validstring[s_String] := 
 Nand[StringMatchQ[s, ___ ~~ "\!\(" ~~ ___], ToString[s] === s ]
Reap[last = Fold[ If[validstring[#1], (Sow[#1]; #2),
      p = StringJoin[#1, ",", #2]] & , First@badsplit , 
    Rest@badsplit]; If[validstring[last], Sow[last]]][[2, 1]]

enter image description here

Of course the best approach is to not use StringSplit in the first place. ( See comments )


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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