# Pattern match sum of terms

I am trying to define a replacement rule for an arbitrary sum of terms in an equation, that returns the x[i] terms along with their coefficients. For example,

eqns = {0 == x + y,
0 == 1 - 8 x,
0 == 1 + 2 x + 4 y + 3 x}


Here's the pattern I tried using

patt = (0 == Plus[Optional[a__], Optional[b_]x[c_], Optional[d__]]])

eqns /. pattern :> b * x[c]


but this outputs

{x, - 8 x, 3 x}


the output I want is something like

{x, - 8 x, {2 x, 3 x}}


For some reason it's defaulting to the 3x replacement instead of the 2x replacement. Is there a way to design a replacement rule that spits out all matches in the expression?

( I would prefer it if it could be written in in the form

eqns /. pattern :> something


)

Your replacement returns only one term because only one term is specified in the pattern. Compare

x + x /. Plus[Optional[a__], Optional[b_] x[c_], Optional[d__]] :> x[c]
(*x*)


and

x + x /. Plus[Optional[a__], Optional[b_] x[c_], Optional[b1_] x[c1_],   Optional[d__]] :> {b x[c], b1 x[c1]}
(*{x, x}*)


Of course, such an approach will not work when you don't know how many terms there will be in the expression. For such cases, there is Repeated pattern that stands for a sequence of any number of terms:

eqns /. (0 == Plus[seq : Repeated[_. _x], ___] :> {seq})
(*{{x}, {-8 x}, {3 x, 2 x}}*)


I also strongly recommend not using patterns Optional[__] anywhere. __ stands for one or more expressions, which means that MMA will try to populate this patterns at least by one expression first and only if it fails, MMA will use Default. An example:

x + x /. Plus[Optional[a__], Longest[seq : Repeated[_. _x]],    Optional[d__]] :> {{seq}, a, d}
(*{{x}, x, 0}*)


Note that even using Longest does not help here. Further, there is no need to use Optional at all in your example because your can just use BlankNullSequence, which stands for zero or more expressions. Finally, Plus is Orderless, which means that you don't need to care about order of the terms inside Plus.

x + x + x /. Plus[x, x, ___] -> True
(*True*)


In fact, this is the reason why Repeated worked in the example above, because Repeated stands for a sequence of expressions which come one after another.