Skip to content

Replace ​

expr rewritten by lhs -> rhs, but ONLY if the whole expression matches — unlike ReplaceAll, this never looks inside subexpressions.

✓ checked against that system · ! checked, with disagreements (hover a chip)Wolfram LanguageReplace✓
Replace(expr, lhs -> rhs)rhs (with wildcards substituted) if expr matches lhs at the top level, else expr unchanged
Replace(expr, {rule1, rule2, …})like the 2-argument form, trying each rule in order and using the first that matches
Replace(expr, {{rules…}, {rules…}})each set of rules on its own, the answers as a list
Typed signatures
TypePackageApplies
(any, expression<Rule> | list<expression<Rule>> | list<list<expression<Rule>>>) -> anycombinatoricsalways

Domain: Collections

Details
  • TOP LEVEL ONLY: this is the difference from compute-engine's own ReplaceAll (Wolfram's /.), which recurses into every subexpression. Replace is Wolfram's own /. restricted to depth 0 — closer to Wolfram's ReplaceAll would actually be ReplaceAll here.
  • Built on BoxedExpression's own match/subs rather than compute-engine's replace method, which (probed) silently no-ops on a literal, non-wildcard match target reached through a boxed Rule.

Examples

Basic #
live ↗
InReplace(x+1,Rule(_a⁡+1,100_a⁡))\mathrm{Replace}(x+1, \mathrm{Rule}(\operatorname{\_a}+1, 100\operatorname{\_a}))Out100x100x

Only the whole expression is tried, so x2x^2 inside the sum is not replaced

live ↗
InReplace(1+x2,Rule(x2,a+b))\mathrm{Replace}(1+x^2, \mathrm{Rule}(x^2, a+b))Outx2+1x^2+1
live ↗
InReplace(x2,Rule(x2,a+b))\mathrm{Replace}(x^2, \mathrm{Rule}(x^2, a+b))Outa+ba+b
live ↗
InReplace(x,[[Rule(x,a)],[Rule(x,b)]])\mathrm{Replace}(x, \bigl\lbrack\bigl\lbrack\mathrm{Rule}(x, a)\bigr\rbrack, \bigl\lbrack\mathrm{Rule}(x, b)\bigr\rbrack\bigr\rbrack)Out[a,b]\bigl\lbrack a, b\bigr\rbrack
Scope #
live ↗
InReplace(b,[Rule(a,1),Rule(b,2)])\mathrm{Replace}(b, \bigl\lbrack\mathrm{Rule}(a, 1), \mathrm{Rule}(b, 2)\bigr\rbrack)Out22

No rule matches, so the expression is unchanged

live ↗
InReplace(x,[Rule(y,2),Rule(z,3)])\mathrm{Replace}(x, \bigl\lbrack\mathrm{Rule}(y, 2), \mathrm{Rule}(z, 3)\bigr\rbrack)Outxx
Properties #

An empty rule list does nothing

live ↗
InReplace(x,[])\mathrm{Replace}(x, \bigl\lbrack\bigr\rbrack)Outxx
live ↗
InReplace(x,[[Rule(x,1)],[Rule(y,2)]])\mathrm{Replace}(x, \bigl\lbrack\bigl\lbrack\mathrm{Rule}(x, 1)\bigr\rbrack, \bigl\lbrack\mathrm{Rule}(y, 2)\bigr\rbrack\bigr\rbrack)Out[1,x]\bigl\lbrack1, x\bigr\rbrack
Possible issues #

unlike ReplaceAll, a match one level down doesn't count

live ↗
InReplace([x+1],Rule(_a⁡+1,100_a⁡))\mathrm{Replace}(\bigl\lbrack x+1\bigr\rbrack, \mathrm{Rule}(\operatorname{\_a}+1, 100\operatorname{\_a}))Out[x+1]\bigl\lbrack x+1\bigr\rbrack
About
Examples9
Checked againstWolfram Language 7 agree
CrosswalkWolfram Language

See also: MatchQ, ReplacePart