# Pattern recognition for products of variables

Pattern recognition doesn't work as I would expect when trying to match products, for example

Cases[a[1] b[1] a[2] b[2], x___ a[k_] b[k_] -> k, All]


{1}

Cases[a[1] b[1] a[2] b[2], a[k_] b[k_] -> k, All]


{}

But none of these two return {1,2} as I would expect. How to cure this problem ?

Thanks.

It works as expected. It matches the whole expression at once:

Cases[a[1] b[1] a[2] b[2], x___ a[k_] b[k_], All]
(* {a[1] a[2] b[1] b[2]} *)


If you want to get all possible matches, please look at ReplaceList, which:

attempts to transform the entire expression expr by applying a rule or list of rules in all possible ways, and returns a list of the results obtained.

ReplaceList[a[1] b[1] a[2] b[2], x___ a[k_] b[k_] :> k]
(* {1, 2} *)

• Thanks a lot for your comment, it was really helpful! Also why does ReplaceList[a[1]^2 , x___ a[k_]^2 :> k] return {} instead of {1} ? Commented Mar 12 at 18:00
• @AdrienMartina why are you using triple blank? Just use the regular blank, and make it optional: ReplaceList[a[1]^2 , x_. a[k_]^2 :> k] . But note that you can use plain Cases in this case. Commented Mar 12 at 19:02
p = a[1] b[1] a[2] b[2];

SequenceCases[List @@ p, {a[k_], b[k_] ...} :> k]


{1, 2}