# Replacing of variables but not subscripts

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?

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):

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


y + Subscript[a, x]

• Thanks. It's bit more general solution, thus it suits me better then the answer above. – Artem Zefirov Apr 11 '18 at 19:36
• 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." – Alan Apr 12 '18 at 1:46

x + Subscript[a, x] /. Subscript[a_, x] :> Subscript[a, z] /. {x -> y, z -> x}

• It works but only for subsripts of a. So, it does not work for Subscript[b_, x], for example. – Henrik Schumacher Apr 11 '18 at 18:57