Replace[x, {{x -> a}, {x -> b},{y->c}}]
gives {a,b,x}
. How to get just {a,b}
from the above expression?
2 Answers
$\begingroup$
$\endgroup$
I assume you're trying to use this for a more general case. Knowing what the general case is would help me know which solution would be generalizable to your situation.
One way is to use ReplaceList with Flatten:
Flatten[ReplaceList[x, {{x -> a}, {x -> b}, {y -> c}}]]
Or more simply:
ReplaceList[x, {x -> a, x -> b, y -> c}]
$\begingroup$
$\endgroup$
Add an extra replacement to each list such that if nothing matches you return Nothing
nullrep = _ :> Nothing
(* _ :> Nothing *)
Replace[x, {{x -> a, nullrep}, {x -> b, nullrep}, {y -> c, nullrep}}]
(* {a, b} *)