2
$\begingroup$

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.

$\endgroup$
3
  • 1
    $\begingroup$ ReplacePart might be useful for this. $\endgroup$ Mar 25, 2020 at 16:06
  • $\begingroup$ 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. $\endgroup$
    – NeAr
    Mar 25, 2020 at 16:08
  • $\begingroup$ Please edit the question to clarify this requirement. $\endgroup$ Mar 25, 2020 at 19:46

2 Answers 2

3
$\begingroup$
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:

enter image description here

$\endgroup$
2
$\begingroup$

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]]
$\endgroup$

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.