I am trying to parse a string, but I have no idea how to solve the following problem

problem = "a { b { c d } e } aa { bb cc }";
answer = {{"a", "b", "c"}, {"a", "b", "d"}, {"a", "e"}, {"aa", "bb"}, {"aa", "cc"}};

So the answer is a path in each sub-list of the list

Any suggestions ?

  • $\begingroup$ can you please enter the problem is Mathematica synatx? Is the problem meant to be: problem = a { b { c d } e } a a { b b c c } ? I do not understand what path node list of the tree information here. You mean TreeForm ? can you give a link that explains what it is? $\endgroup$ – Nasser Jan 17 '15 at 9:02
  • $\begingroup$ now modified. sorry for ambiguity. $\endgroup$ – marsiano Jan 17 '15 at 9:08

I may have misunderstood the requirement but this seems to work for the example at least:

problem = "a { b { c d } e } aa { bb cc }";

Map[Flatten, StringSplit[problem] //. 
 {head___, x_, "{", Shortest[y__], "}", tail___} :> 
 {head, Sequence @@ Thread[{x, {y}}], tail}]

(* {{"a", "b", "c"}, {"a", "b", "d"}, {"a", "e"}, {"aa", "bb"}, {"aa", "cc"}} *)
|improve this answer|||||
  • $\begingroup$ Thanks Woods. I think you gave me a correct answer! $\endgroup$ – marsiano Jan 19 '15 at 2:34
  • $\begingroup$ some explanation would have been helpful. $\endgroup$ – törzsmókus Dec 12 '18 at 21:10

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.