2
$\begingroup$

Having a string like :

"{Aaaa -> a, Bbbb- > b, Cccc -> , Ddddd -> c, Eeeee -> , Fffff -> e}"

I want to delete the parts that contain "a word" + "-> ," and replace them just with "," to have result like

"{Aaaa -> a, Bbbb- > b, Ddddd -> c, Fffff -> e}"

So that I can bring this ToExpression[]

Thanks.

$\endgroup$
2
$\begingroup$

You can use StringCases.

str = "{Aaaa -> a, Bbbb -> b, Cccc -> , Ddddd -> c, Eeeee -> , Fffff -> e}";
ToExpression@StringCases[str, WordCharacter .. ~~ " -> " ~~ WordCharacter ..]

{Aaaa -> a, Bbbb -> b, Ddddd -> c, Fffff -> e}

$\endgroup$
2
$\begingroup$

You can also use a combination of StringSplit, SyntaxQ and Pick:

str = "{Aaaa -> a, Bbbb- > b, Cccc -> , Ddddd -> c, Eeeee -> , Fffff ->  e}";

str2 = Pick[#, SyntaxQ /@ #] &@StringSplit[str, "," | "{" | "}"]
(* {"Aaaa -> a", " Ddddd -> c", " Fffff -> e"} *)

ToExpression@str2
(* {Aaaa -> a, Ddddd -> c, Fffff -> e} *)
$\endgroup$
1
  • $\begingroup$ This is also a nice solution, thank you! $\endgroup$
    – SuTron
    Apr 3 '15 at 12:22
1
$\begingroup$

Or the StringReplace version:

In[3]:= StringReplace[str, WordCharacter .. ~~ " -> ," -> ""]
Out[3]= "{Aaaa -> a, Bbbb -> b,  Ddddd -> c,  Fffff -> e}"

In[4]:= ToExpression@%
Out[4]= {Aaaa -> a, Bbbb -> b, Ddddd -> c, Fffff -> e}
$\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.