# Extract variable from subexpression

I have an expression of the form a1*x*b1^2 + a2*y*c1^2 I want to extract the x and y from the expressions. a_, b_, and c_ are the only types of variables that appear in the expression . Form of x and y are not known. Anyone know how? x and y are not necessarily numbers .

• I tried exp/a[#]/;MemberQ[exp,a[#], Infinity]&Range[3]. But it did not work. Mar 16 '17 at 14:46

f[expr_] := Module[
{vars = Variables[Level[expr, {-1}]]},
vars = Pick[vars,
Switch[#, "a" | "b" | "c", True, _,
False] & /@
(StringTake[ToString[#], 1] & /@ vars)];
((CoefficientList[expr, vars] // Flatten) /.
(0 :> Nothing))[[1]]]

expr1 = a1*x*b1^2 + a2*y*c1^2;

f /@ (List @@ expr1)

(*  {x, y}  *)

expr2 = a1*2*b1^2 + a2*y*c1^2;

f /@ (List @@ expr2)

(*  {2, y}  *)


Note that Mathematica may alter the form of an expression from what is manually entered

expr3 = a1*(y^2 + 2 x)*b1^2 + a2*y*c1^2

(*  a2 c1^2 y + a1 b1^2 (2 x + y^2)  *)

f /@ (List @@ expr3)

(*  {y, 2 x + y^2}  *)

• thanks a lot. It took me while to look up the commands but I understand it now. Thanks a lot. Mar 16 '17 at 15:20