# Select forms of indexed variables from an expression

I want to select some certain terms from a long expression. The expression contains parts like

k[1,2](k[3,4]+k[5,6])/k[2,3]


I hope to get all terms with the form of

k[a,b]+k[c,d]


where a, b, c, d, can be arbitrary integers. I tried

Select[expr,MemberQ[#,k[a_, b_]+k[c_, d_]]&]


but it didn't work. Is there a way to realized this?

In addition, I also want to use

FullSimplify[expr]/.k[a_, b_] :> k[b, a]


to simplify the expression but when I apply it to the expression, nothing is simplified. Can someone help me with this? Thanks.

• try Cases[expr, Plus[_k, __k], All]? – kglr Mar 10 at 12:33
• Hi, thank you a lot, it worked! Can you please explain why there are two underscores before the second k? Also, I need to extend the sequences to k[a,b,c,d] for further calculation but I don't know why this function failed if k has a length of 4. – ntply Mar 10 at 13:44
• ntly, posted an answer explaining why Plus[_k,_k] does not work. – kglr Mar 10 at 14:10

expr = k[1, 2] (k[3, 4] + k[5, 6])/k[2, 3]


You can use Cases as follows:

Cases[expr, HoldPattern[_k + _k], All]


{k[3, 4] + k[5, 6]}

expr2 = k[1, 2, 3, 4] (k[3, 4, 5, 1] + k[5, 6, 1, 7])/k[2, 3, 8, 9];
Cases[expr2, HoldPattern[_k + _k], All]


{k[3, 4, 5, 1] + k[5, 6, 1, 7]}

Note: We cannot use the simpler pattern _k + _k because it evaluates to 2 _k before pattern matching gets to work and Cases returns {} because no part of expr matches 2 _k.

• Thank you for your explanation! In addition, do you know why the Cases function does not work for expression consists of k[a,b,c,d]? For example, k[1, 2,3,4] (k[3, 4, 5, 1] + k[5, 6, 1,7])/k[2, 3, 8, 9] – ntply Mar 10 at 14:16
• @ntply, it does work for expr2 = k[1, 2, 3, 4] (k[3, 4, 5, 1] + k[5, 6, 1, 7])/k[2, 3, 8, 9] too. – kglr Mar 10 at 14:26
• Yeah, it does, I might have some typo before, Thanks again for your help :) – ntply Mar 10 at 14:47