0
$\begingroup$

Let's consider I have following string:

"{a-> POR, b-> D610, c-> 0, d-> \"300/7\", e -> \"1/400\"}"

How can I run over and update anything that is between " " to be an expression. So that having following result:

   {a-> POR, b-> D610, c-> 0, d-> ToExpression["300/7"], e -> ToExpression["1/400"]}

Thanks.

$\endgroup$
4
  • $\begingroup$ The quotes stay strangely. The fragment "5/2"" does not seem to be correct. $\endgroup$ Commented Mar 30, 2015 at 11:12
  • $\begingroup$ "5/2"" this is correct. I just need to replace everything that is in quotes to expression. $\endgroup$
    – SuTron
    Commented Mar 30, 2015 at 11:30
  • $\begingroup$ No, please see the update $\endgroup$
    – SuTron
    Commented Mar 30, 2015 at 11:40
  • $\begingroup$ Yes, you are right! $\endgroup$
    – SuTron
    Commented Mar 30, 2015 at 11:48

1 Answer 1

1
$\begingroup$
ToExpression[
  "{a-> POR, b-> D610, c-> 0, d-> \"300/7\", e -> \"1/400\"}"
  ] /. s_String :> Defer @ ToExpression[s]
{a -> POR, b -> D610, c -> 0, d -> ToExpression["300/7"], 
 e -> ToExpression["1/400"]} 

response to comment:

ToExpression[
  "{a-> POR, b-> D610, c-> 0, d-> \"300/7\", e -> \"1/400\"}"
] /. (lhs : Except[d] -> rhs_String) :> (lhs -> Defer @ ToExpression[rhs])
{a -> POR, b -> D610, c -> 0, d -> "300/7", 
 e -> ToExpression["1/400"]} 
$\endgroup$
8
  • $\begingroup$ Can you please add a check here? e.g. to check if the left of the rules is "d", skip it? $\endgroup$
    – SuTron
    Commented Mar 30, 2015 at 13:52
  • 1
    $\begingroup$ @SuTron like in the edit? $\endgroup$
    – Kuba
    Commented Mar 30, 2015 at 13:56
  • $\begingroup$ Yes, thank you! $\endgroup$
    – SuTron
    Commented Mar 30, 2015 at 14:01
  • $\begingroup$ Sorry for being nasty :) but is it possible to have in the output already evaluated ToExpression["300/7"] view, instead of "ToExpression["300/7"]"? $\endgroup$
    – SuTron
    Commented Mar 30, 2015 at 14:08
  • 1
    $\begingroup$ @SuTron yes, skip `Defer, no problem :) $\endgroup$
    – Kuba
    Commented Mar 30, 2015 at 14:09

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.