Parse, pattern match and extract functions of variables

From expressions like i σ[1, 1] + p ** x σ[1, 1], I want to be able to extract and separate any functions of p and x. For example, it would return a list of triplets {i,σ [1, 1], 1}, {1,σ[1, 1], p ** x}, but it should work for generic polynomial functions of x and p. Is this possible?

I want to be able to pattern match a product like A p**p** ... x**x ... **x where A is the coefficient and the noncommutative product is always ordered with p before x but has an unknown number of terms x and p.

More examples:

p**p**x 2y -> {2y, 1, p**p**x}

σ[1,1] 2y -> {2y, σ[1,1], 1}

g -> {g, 1, 1}

p -> {1, 1, p}

p**p**x -> {1, 1, p**p**x}

• Does Cases[expr, a_. NonCommutativeMultiply[___, p, ___, x, ___]] work for you? Commented Mar 20 at 15:28
• @Domen yes thanks I think I figured it out
– Luca
Commented Mar 26 at 0:15
• @Domen is there a way to make it return 1 when a match is not found? I am using the rule /. a_ s_[Sigma] NonCommutativeMultiply[i___, p, j___, x, k___] -> {a,s,NonCommutativeMultiply[i, p, j, x, k]} but sometimes a, s or NonCommutative... may be missing, in which case I want a 1 in the list
– Luca
Commented Mar 26 at 0:50
• Can you please edit the question and include an example of your expression? The one that contains both kind of terms. Commented Mar 26 at 8:45

expr = i σ[1, 1] + p ** x σ[1, 1]
Cases[expr, Optional[a_, 1] (σ : σ[__]) *
(b : NonCommutativeMultiply[___, p, ___, x, ___]) |
(Optional[a_, 1] (σ : σ[__]) b_ : 1) :> {a, σ, b}]
(* {{i, σ[1, 1], 1}, {1, σ[1, 1], p ** x}} *)

• Thanks. for some reason Cases[p ** x, NonCommutativeMultiply[, p, ___, x, ___]] doesn't work when it is only an expression of p and x on its own. it also doesn't work for Cases[p, NonCommutativeMultiply[, p, , x, ___]]. Is there a way to make Cases[p, NonCommutativeMultiply[, p, ___, x, ___]] return p instead of {}?
– Luca
Commented Mar 26 at 11:53
• That's why I told you to please include all possible types of expressions and expected output in your question above :) I'll fix my answer after you do that. Commented Mar 26 at 12:01
• Thanks, I found a way by just using cases to extract the expression and add it to a list and then delete it one by one. For example I extract p**x and then delete it and then do the same for $\sigma$. But for some reason Cases does not work when the expression is just the symbol I am looking for. For example Cases[p,p] returns {}
– Luca
Commented Mar 26 at 12:09
• do you know how to get around this Domen?
– Luca
Commented Apr 5 at 15:12