# How to protect pattern or subexpression when distributing / expanding expression?

I've got an expression like

expr = (1-x)(a+b)


that I would like to distribute / expand while keeping factors of (1-x) intact, i.e. the result should in the above example should look like

(1-x)a + (1-x)b


I know that for the explicit example given here, Expand[expr,(a+b)] would yield the desired result. However, I would need a solution where (a+b) can be any arbitrary algebraic expressions that is distributed with (1-x) being left untouched.

Is there maybe a way to define a pattern that matches my (1-x) terms that I can than hold while distributing?

-
HoldForm[1-x](a+b) // Expand? –  Ｊ. Ｍ. Oct 30 '12 at 11:17
Yes, but for an already existing expression (that is somewhat more complicated than my example) - how do I tell Mathematica to hold all occurrences of (1-x)? –  janitor048 Oct 30 '12 at 11:27
Again, look up HoldForm[]. And while you're at it, Defer[] too. –  Ｊ. Ｍ. Oct 30 '12 at 11:28

Does expr /. (1-x) -> HoldForm[1-x] work? That should Hold all occurences of (1-x) in your expression.

-
provided you remember to do Expand afterwards ;-) –  chris Oct 30 '12 at 12:06
Thanks, I didn't think of substituting the (1-x) term with its HoldForm variant.. –  janitor048 Oct 30 '12 at 16:04

We could substitute a variable for the expression we wish to preserve, expand the result, and then substitute the expression back for the variable. Like so:

expandExcept[expr_, exception_] :=
Module[{u}, Expand[expr /. exception -> u] /. u -> exception]

expandExcept[(1-x)(a+b), 1-x]
(* a (1-x) + b (1-x) *)

expandExcept[(1-x)/(a+b)+(1-x)^2(c+d)^3, 1-x]
(* (1-x)/(a+b) + c^3 (1-x)^2 + 3 c^2 d (1-x)^2 + 3 c d^2 (1-x)^2 + d^3 (1-x)^2 *)


This has the advantage over a solution based upon HoldForm in that the result remains a valid algebraic expression.

-
...and by using a formal variable like \[FormalU], one could skip the use of Module[] in expandExcept[]... –  Ｊ. Ｍ. Oct 30 '12 at 22:35