6.48 How to replace patterns in expressions

6.48.1 example 1

by Andrzej Kozlowski on math group, July 2010:

Suppose in the expression 2/3 I + x/y I you wish to replace all fractions (that is 2/3 and x/y) by r and I by d. Without worrying about evaluation you can do this as follows:

Unevaluated[Unevaluated[(2/3)*I + (x/y)*I] /. HoldPattern[(x_)/(y_)] -> r] 
       /. HoldPattern[I] -> d 
 
Out[200]= -d + d*(1 - x^2/2)
 

If you allow the expression to evaluate the patterns will no longer match. For example, with only one Unevaluated you will get

Unevaluated[(2/3)*I + (x/y)*I] /. HoldPattern[(x_)/(y_)] -> 
       r /. HoldPattern[I] -> d 
 
Out[201]= -I + I*(1 - x^2/2)
 

6.48.2 example 2

question: I want to replace y for x everywhere except in Exp[x].

Answer by Bob Hanlon on the net. messageID=7120881&tstart=0

Remove["Global`*"] 
expr = a*x + b*x^2 - c*Exp[x]; 
expr /. {Exp[x] -> z, x -> y} /. z -> Exp[x] 
 
Out[211]= (-c)*E^x + a*y + b*y^2