4
$\begingroup$

Is there a good way to act with a StringReplace on all strings in an expression? The problem is that I want to replace some part of a string but not on a single string or on a list of strings but in some complicated expression where it is not clear where the string might be (so the function would need to test for this).

Example: Say that for in an expression of the type

f["text"]+g[h["some text"]] j[a,"some more text"]^n

we want to replace "text" inside any string with "replaced text" (in the same manner as StringReplace would do this if directly applied to all the strings in question).

The real expression would be bigger and so finding by hand where the strings are is not a solution.


As is often the case writing the question clearly helps to immediately answer it. So one possible answer to the question is

allStringsReplace[expr_, replacement_] := 
 expr /. a_String :> StringReplace[a, replacement]

I might as well still ask the question as there might be a better answer or maybe someone else might someday be interested in the answer.

$\endgroup$
  • 3
    $\begingroup$ I'm afraid this is the way to go :) $\endgroup$ – Kuba Feb 20 '18 at 13:04
3
$\begingroup$

As is often the case writing the question clearly helps to immediately answer it. So one possible answer to the question is

allStringsReplace[expr_, replacement_] := 
 expr /. a_String :> StringReplace[a, replacement]
$\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.