ReplaceAll

expr /. rule replaces all occurences of the LHS of rule with the RHS of rule in expr.

expr /. {r1, r2, ...} performes the same operation as expr /. rule, but evaluating each r_n in sequence.

Attributes[ReplaceAll] := {Protected}

Simple examples

In[1]:= ((2^(x^2 + 1) + x^2)) /. ((x^2 -> y))
Out[1]= 2^(y + 1) + y

If no match is found, ReplaceAll evaluates to an unchanged expr:

In[2]:= ((2^(x^2 + 1) + x^2)) /. ((z^2 -> y))
Out[2]= 2^(x^2 + 1) + x^2

ReplaceAll works within Orderless expressions as well (such as Plus):

In[3]:= ((a + b + c + c^2)) /. ((c^2 + a -> d))
Out[3]= b + c + d

ReplaceAll can use named patterns:

In[4]:= ((a + b + c + d)) /. ((x_Symbol + y_Symbol -> x^y))
Out[4]= a^b + c + d
In[5]:= ((a + 2*b + 5*c)) /. ((c1_Integer*a_Symbol -> 99*a))
Out[5]= a + 99*b + 99*c

Further examples

ReplaceAll can be used to replace sequences of expressions:

In[1]:= ((a + b + c + d)) /. ((a + amatch___ -> foo[amatch]))
Out[1]= foo[b, c, d]

The Head of functions can be replaced just as the subexpressions:

In[2]:= ((x + 2)[5, 6]) /. ((2 + x -> Plus))
Out[2]= 11
In[3]:= ((a*b*c*d)) /. ((_Symbol -> 2))
Out[3]= 2[2, 2, 2, 2]