# Replace two objects in an expression

So I have a long expression that looks like this:

a (e1.e3)^2 (f1.e2)^2 + b (e1.e2)^2 (f1.e3)^2 + c e1.e3 e2.e3 f1.e2 f2.e1 + ...


What I want to do is to replace the first occurrence of, say, e1 with one term and the second with another, say x1 and y1. Furthermore, I would like the expression to be symmetric in the end. For example, I would like to have

(e1.e3)^2 --> x1.e3 y1.e3


and

e1.e3 e2.e3 f1.e2 f2.e1 --> x1.e3 e2.e3 f1.e2 f2.y1 + y1.e3 e2.e3 f1.e2 f2.x1


How do I come up with a replacement rule that will do the job?

• Do you mean string, or do you mean expression? It looks like an expression to me, so you should change the title. Nov 9 '20 at 21:07
• Thanks, @flinty! done. Nov 9 '20 at 21:13
• Is there a typo in the first example ( shouldn't it be (e1.e3)^2 --> x1.e3 + y1.e3 )?
– kglr
Nov 9 '20 at 23:28

Try the following. Let us introduce two rules:

rule1 = {Dot[e1, a_]^2 :> x.a*y.a, Dot[a_, e1]^2 :> x.a*y.a};
rule2 = {Times[Dot[e1, a_], b___, Dot[c_, e1]] :>
Times[Dot[x, a], b, Dot[c, y]] + Times[Dot[y, a], b, Dot[c, x]],
Times[Dot[a_, e1], b___, Dot[c_, e1]] :>
Times[Dot[a, x], b, Dot[c, y]] + Times[Dot[a, y], b, Dot[c, x]],
Times[Dot[a_, e1], b___, Dot[e1, c_]] :>
Times[Dot[a, x], b, Dot[y, c]] + Times[Dot[a, y], b, Dot[x, c]],
Times[Dot[e1, a_], b___, Dot[c_, e1]] :>
Times[Dot[x, a], b, Dot[c, y]] + Times[Dot[y, a], b, Dot[c, x]]
}


Let

expr=a (e1.e3)^2 (f1.e2)^2 + b (e1.e2)^2 (f1.e3)^2 + c e1.e3 e2.e3 f1.e2 f2.e1


expr /. rule1 /. rule2