It's an extremely brief question. I want to replace all variables in an expression to another ones, say $x \rightarrow y$. But the command

x + Subscript[a, x] /. x -> y

replaces also the subscript. How can I do replacements while leaving the Subscript object unchanged?


2 Answers 2


When you want to do replacements with a pattern that shouldn't be changed, I like to use multiple replacement rules (as in this answer):

    x + Subscript[a, x],
        s_Subscript :> s, (* pattern to avoid *)
        x -> y

y + Subscript[a, x]

  • 1
    $\begingroup$ Thanks. It's bit more general solution, thus it suits me better then the answer above. $\endgroup$ Apr 11, 2018 at 19:36
  • 1
    $\begingroup$ It may be worth quoting the documentation to explain why this works: "The first rule that applies to a particular part is used; no further rules are tried on that part or on any of its subparts." $\endgroup$
    – Alan
    Apr 12, 2018 at 1:46

It's an extremely brief answer:

x + Subscript[a, x] /. Subscript[a_, x] :> Subscript[a, z] /. {x -> y, z -> x}
  • $\begingroup$ Thanks. Could you clarify briefly whether the command x + Subscript[a, x] /. Subscript[a, x] -> Subscript[a, z] /. {x -> y, z -> x} is wrong. That is, can we replace function-like notation a_ with a, and delayed reduce :> with a simple reduce symbol -> ? $\endgroup$ Apr 11, 2018 at 18:55
  • $\begingroup$ It works but only for subsripts of a. So, it does not work for Subscript[b_, x], for example. $\endgroup$ Apr 11, 2018 at 18:57
  • $\begingroup$ Anyway, your answer is witty. I thought, that there should be something more straightforward. $\endgroup$ Apr 11, 2018 at 19:03

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.