Let's say I have a piece of code:
Hold[{code1,
"asdad " <> ToString[testa] <> " adsd " <> ToString[testb],
code2}] (*MWE ofc*)
which I want to convert. Each StringJoin[...]
should be replaced so I will get:
Hold[{code1, StringForm["asdad `` adsd ``", testa, testb], code2}]
I have an answer but maybe one may show shorter approach:
Hold[{code1, "asdad " <> ToString[testa] <> " adsd " <> ToString[testb], code2}
] /. HoldPattern[StringJoin[x__]
] :> RuleCondition@(
StringForm[StringJoin @@ (Hold[x] /. _ToString :> "``"),
##] & @@ Cases[Hold[x], HoldPattern[ToString[z_]] :> z]
) // InputForm
Hold[{code1, StringForm["asdad `` adsd ``", testa, testb], code2}]
Edit: This solution is not perfect. It evauates testa
and testb
, does not matter in my case but for generality let's assume they may not be evaluated. Also, referring to first of Mr.Wizard's suggestions: StringJoin
expressions may appear or different levels too.
StringJoin
objects be replaced, or only those at level 2, or only certain ones by position? $\endgroup$testa
andtestb
get evaluated. Is that acceptable? $\endgroup$Attributes
ofStringForm
on your system? $\endgroup$Protected
. Hmm, it seems they are, I've missed that because it does not make a difference for my purposes. $\endgroup$