How to replace the first occurence in an expression instead of replacing all?
Well here's a way. Find the position of the first occurrence of x
:
expr = HoldForm[x + 2 + 4 + x];
pos = Position[expr, x, -1, 1];
Then:
ReplacePart[expr, pos -> 4]
4 + 2 + 4 + x
Another way:
hf = HoldForm[x + 2 + 4 + x]
i = 0
hf /. (x :> 4 /; i++ == 0)
4 + 2 + 4 + x
Edit
For order preserving as Jens says, I changed Attributes
ClearAttributes[Plus, Orderless]
HoldForm[7 + x + 2 + 4 + x + 5] /. f___ + x + l___ :> f + 4 + l
7 + 4 + 2 + 4 + x + 5
And you can revert by SetAttributes[Plus, Orderless]
Origin
How about this
HoldForm[x + 2 + 4 + x] /. x + a___ -> 4 + a
4 + 2 + 4 + x