6
$\begingroup$

I am trying to use an efficient notation for the timing of sounds that i can play in Mathematica.

I would like to parse the string

"{ab{c{de}}f}" 

as the list

{a,b,{c,{d,e}},f}.

The idea is that the sublists should have a duration equal to a single element of their enclosing list.

This seems straightforward, but I cannot see a simple way to do it.

I could use ToExpression[] if I could turn

"{ab{c{de}}f}" 

into the string

"{a,b,{c,{d,e}},f}", 

but I am having trouble doing that. I am confident that I can solve this with something klunky, but I suspect that there is an elegant way to do it.

Thanks,

$\endgroup$
11
$\begingroup$
Block[{Times = Sequence},
 ToExpression@ StringRiffle@ Characters@ "{ab{c{de}}f}"
 ]

(*  {a, b, {c, {d, e}}, f}  *)
$\endgroup$
  • $\begingroup$ This is the best answer. I did not know about Block[{Times=Sequence} ...]. This is the kind of answer I was hoping for. Thank you. $\endgroup$ – Steve E May 6 '16 at 1:59
7
$\begingroup$
str = "{ab{c{de}}f}";
str2 = StringReplace[str, x : LetterCharacter ~~ y : LetterCharacter :> x ~~ "," ~~ y];

Block[{Times = Sequence}, ToExpression[str2]]

{a, b, {c, {d, e}}, f}

$\endgroup$
6
$\begingroup$
str = StringReplace["{ab{c{de}}f}",x : LetterCharacter :> "," <> x <> ","];
Quiet[ToExpression[str] /. Null :> Nothing]

(*{a, b, {c, {d, e}}, f})*
$\endgroup$

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.