# How to replace a sub-expression when it implicitly exists in an expression

In order to make my question clear, I would like to use a simple expression as an toy example.

Suppose we have an expression, which is,

f = a + 2*b + c


Now I want to replace sub-expression (a+b) with term1, and (b+c) with term2, so that I can obtain the result like

f = term1 + term2


However, I tried functions Replace and ReplaceAll in Mathematica and the results are

[in] f = Replace[f, {(a + b) -> term1, (b + c) -> term2}]
[out] f = a + 2b + c
[in] f = ReplaceAll[f, {(a + b) -> term1, (b + c) -> term2}]
[out] f = a +2b + c


which does not make any changes.

So I was wondering if choose the wrong functions? Or there are some other tricks can be used to achieve this goal.

Simplify has an optional second argument which instructs Simplify to consider this additional information during the simplification process. This can help when the replacement you want is simpler than what you have.

f = a + 2*b + c;
Simplify[f,{a+b==term1,b+c==term2}]


instantly gives you

term1+term2


Try this:

f = a + 2*b + c;
f /. {a -> term1 - b, c -> term2 - b}

(* term1 + term2 *)


Have fun!

• This way is tricky but useful! – Yuejiang_Li Oct 11 '19 at 2:29