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 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].

Examples

open allclose all

Basic Examples  (4)

Replace by default applies rules only to complete expressions:

It does not map down to subparts:

A list of lists of rules gives a list of results:

Use Replace in operator form:

Apply a single possible replacement:

Apply the first matching rule:

Apply each rule separately:

Scope  (15)

If no rule matches, the original expression is returned:

Replace at level 1:

Replace elements of a list that yield True when a test function is applied:

Replace elements of a list that satisfy a Boolean expression:

Replace elements of a matrix with a particular head:

Replace the deepest parts of the expression, i.e. those with no subparts:

Replace at levels 1 through 3:

Replace at levels 0 through 2:

Replace at all levels:

Replace also works with RuleDelayed:

Structurally insert into a held expression:

Do not evaluate the right-hand side of the rule before doing the replacement:

Evaluate the right-hand side before replacement:

Dispatch can be used in place of a list of rules:

Association can be used in place of a list of rules:

Apply a function to all values in an Association:

Replace an Association with the key and value reversed:

Extract all rules in Association to a list:

Replace at level 1, destructuring values that are themselves associations:

Options  (2)

Heads  (2)

By default, heads are not separately matched against the patterns:

Use the option Heads->True to replace heads:

With Heads->True, heads are treated as being at the same depth as the arguments:

This is consistent with how levels are generally treated:

As a result, Heads->True has no effect on the default level spec of {0}:

Applications  (1)

Define a function f:

Normally, it will be repeatedly evaluated until a final result is reached:

Hold the input and replace it using the DownValues of f to inspect a single step of the evaluation:

Proceed one level further:

Properties & Relations  (12)

An empty list is considered to have no matching rules:

When a list of lists is used for replacement, the result is a list of the same length:

The level specification All is equivalent to {0,-1} and {0,}:

If a rule matches at multiple levels, Replace will transform all matching subexpressions:

See the order in which the replacements occurred:

When multiple levels are given, Replace scans the expression using a depth-first search:

Replace replaces a whole expression by default:

It also allows specific levels to be replaced:

ReplaceAll replaces any matching part:

Replace with level spec All will attempt to replace every subexpression exactly once:

ReplaceAll replaces the largest subexpressions it can and then stops:

ReplaceRepeated repeatedly applies ReplaceAll until the expression stops changing:

Replace matches parts at a particular level against a pattern:

ReplacePart rewrites subexpressions at a particular position:

ReplaceList gives a list of results using all possible matches:

Replace gives the first, canonical match:

Replace can transform a complete association:

But when it enters an association it will only replace values, not keys:

Replace matches individual expressions in a given level:

SequenceReplace matches sequences of expressions in the first level:

Replace[expr,lhsrhs] returns a transformed result if and only if MatchQ[expr,lhs] yields True:

Possible Issues  (2)

Applying a long list of rules can be slow:

Using Dispatch can be significantly faster:

Associations can be used to specify replacement rules, but the keys are treated as Verbatim values:

Compare with the following:

The list of rules equivalent to the association is the following:

Wolfram Research (1988), Replace, Wolfram Language function, https://reference.wolfram.com/language/ref/Replace.html (updated 2014).

Text

Wolfram Research (1988), Replace, Wolfram Language function, https://reference.wolfram.com/language/ref/Replace.html (updated 2014).

CMS

Wolfram Language. 1988. "Replace." Wolfram Language & System Documentation Center. Wolfram Research. Last Modified 2014. https://reference.wolfram.com/language/ref/Replace.html.

APA

Wolfram Language. (1988). Replace. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/Replace.html

BibTeX

@misc{reference.wolfram_2024_replace, author="Wolfram Research", title="{Replace}", year="2014", howpublished="\url{https://reference.wolfram.com/language/ref/Replace.html}", note=[Accessed: 23-November-2024 ]}

BibLaTeX

@online{reference.wolfram_2024_replace, organization={Wolfram Research}, title={Replace}, year={2014}, url={https://reference.wolfram.com/language/ref/Replace.html}, note=[Accessed: 23-November-2024 ]}