Suppose I have some rule, e.g. Re[x_] :> (x + Conjugate[x])/2. I want to apply it to all matching sub-expressions in some expression, excluding any sub-expressions that are located somewhere under heads Hold[…] or Function[…] (at any depth). What is the simplest way to do that? Can it be done without explicit filtering of positions?

For example, the result of replacement in the expression:

{z + Re[a], Hold[1 + Re[b]], Function[z, Abs[Re[c]]]}

should be

{z + (a + Conjugate[a])/2, Hold[1 + Re[b]], Function[z, Abs[Re[c]]]}

where Re[b] and Re[c] are left unmodified, because they are located under Hold and Function.

  • $\begingroup$ Vladimir, an example of some expression would make it so much easier to answer your question. $\endgroup$
    – kglr
    Commented Sep 1, 2019 at 1:44
  • 1
    $\begingroup$ It seems that my question is a duplicate of stackoverflow.com/q/6451802/305118 $\endgroup$ Commented Sep 1, 2019 at 2:43

1 Answer 1


Just include the patterns you want to avoid in your replacement rule:

    {z + Re[a], Hold[1 + Re[b]], Function[z, Abs[Re[c]]]},
        h:(_Hold | _Function) :> h,
        Re[x_] :> (x+Conjugate[x])/2

{z + 1/2 (a + Conjugate[a]), Hold[1 + Re[b]], Function[z, Abs[Re[c]]]}


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.