Replace

Replace[expr,rules]
applies a rule or list of rules in an attempt to transform the entire expression expr.

Replace[expr,rules,levelspec]
applies rules to parts of expr specified by levelspec.

Replace[rules]
represents an operator form of Replace that can be applied to an expression.

Details and OptionsDetails and Options

  • The rules must be of the form lhs->rhs or lhs:>rhs.
  • A list of rules can be given. The rules are tried in order. The result of the first one that applies is returned. If none of the rules apply, the original expr is returned.
  • If the rules are given in nested lists, Replace is effectively mapped onto the inner lists. Thus Replace[expr,{{r11,r12},{r21,},}] is equivalent to {Replace[expr,{r11,r12}],Replace[expr,{r21,}],}.
  • Delayed rules defined with :> can contain /; conditions.
  • Replace uses standard level specifications:
  • nlevels 1 through n
    Infinitylevels 1 through Infinity
    Allall levels, including zero
    {n}level n only
    {n1,n2}levels n1 through n2
  • The default value for levelspec in Replace is {0}, corresponding to the whole expression.
  • A positive level n consists of all parts of expr specified by n indices.
  • A negative level -n consists of all parts of expr with depth n.
  • Level -1 consists of numbers, symbols, and other objects that do not have subparts.
  • If levelspec includes multiple levels, expressions at deeper levels in a given subexpression are matched first.
  • With the option setting Heads->True, Replace includes heads of expressions, and their parts.
  • Replacements are performed to parts specified by levelspec even when those parts have Hold or related wrappers.
  • Replace[rules][expr] is equivalent to Replace[expr,rules].

ExamplesExamplesopen allclose all

Basic Examples  (4)Basic Examples  (4)

Replace by default applies rules only to complete expressions:

In[1]:=
Click for copyable input
Out[1]=

It does not map down to subparts:

In[2]:=
Click for copyable input
Out[2]=

A list of rules gives a list of results:

In[1]:=
Click for copyable input
Out[1]=

Use Replace in operator form:

In[1]:=
Click for copyable input
Out[1]=

Apply a single possible replacement:

In[1]:=
Click for copyable input
Out[1]=

Apply the first matching rule:

In[2]:=
Click for copyable input
Out[2]=

Apply each rule separately:

In[3]:=
Click for copyable input
Out[3]=
Introduced in 1988
(1.0)
| Updated in 2014
(10.0)
Translate this page: