# How to replace with an exception

I would like to replace the following expression:

sp[p1, p1] + 2*sp[p1, p1]*sp[p2, p2] /. sp[p1, p1] -> sp[p2, p2]


BUT I do not want to replace the second term only the first. BTW, the sp stands for "scalar product" in my notation.

• ReplacePart might be useful for this. Mar 25, 2020 at 16:06
• The above example is fairly easy. My actual expression is much more complicated thats why I need a rule to replace sp[p1,p1]->sp[p2,p2] but I should not replace the combination of the two scalarproducts.
– NeAr
Mar 25, 2020 at 16:08
• Please edit the question to clarify this requirement. Mar 25, 2020 at 19:46

expr = sp[p1, p1] + 2*sp[p1, p1]*sp[p2, p2];

rules = {pat : HoldPattern[Times[___, _sp, ___, __sp, ___]] :> pat,
sp[p1, p1] -> sp[p2, p2]};

ReplaceAll[rules] @ expr

 sp[p2, p2] + 2 sp[p1, p1] sp[p2, p2]


### ReplaceAll >> Details:

One can use Replace with a level specification:

Replace[sp[p1, p1] + 2*sp[p1, p1]*sp[p2, p2], sp[p1, p1] -> sp[p2, p2], 1]


For ReplacePart mentioned in the comment by @DanielLichtblau:

ReplacePart[sp[p1, p1] + 2*sp[p1, p1]*sp[p2, p2], 1 -> sp[p2, p2]]