Wolfram: ReplaceAll
ReplaceAll
ReplaceAll[expr, rules]
🔸 SHORT SYNTAX: expr /. rules
- Replace expr by transformation Rules rules
- rules can be a single rule or a list of rules.
- Match all levels of expr. 〔see Wolfram: Pattern Matching and Level Spec〕
- Match is done at top level first. e.g. level 0 to Infinity, level 1 to Infinity, level 2 to Infinity, etc.
- When a rule match, replace is done immediately. Subsequent rule is not matched against the already replaced parts.
- The replacement is not considerd for match.
- Replace is done for all occurrences.
💡 TIP: this is the most frequently used.
ReplaceAll[ {a, {c, {4}}, {7, d}}, x_Integer -> x + 1] (* {a, {c, {5}}, {8, d}} *)
ReplaceAll[ {1, {2, {3, {4}}}}, {_Integer, {_Integer}} -> x] (* {1, {2, x}} *)
(* once a part is replaced, that part is not used to match. *) ReplaceAll[ {1, {2, {3, {4}}}}, { {2,_} -> x, 3 -> z } ] (* {1, x} *)
(* the replacement is not considerd for match. *) ReplaceAll[ {1, {2, {3, {4}}}}, { 1 -> x, x -> z } ] (* {x, {2, {3, {4}}}} *)
(* match is done at top level first. e.g. level 0 to Infinity, level 1 to Infinity, level 2 to Infinity, etc. this is especially important if a pattern that is non-flat, such as Blank[] *) ReplaceAll[ {1, {2, {3, {4}}}}, {_Integer, _} -> x] (* x *) ReplaceAll[ {1, {2, {3, {4}}}}, _ -> x] (* x *)
(* replace is done for all occurrences *) ReplaceAll[ {1, {2, {3, {4}}}}, _Integer -> x] {x, {x, {x, {x}}}}