You can find them all using
Cases[{f^2, g^3, k^p, h}, x_^n_. :> n]
Same for the other one
Cases[{f[a], 2 f[b]}, any_. f[x_] :> x]
(* {a, b} *)
Or for the above second example, you do not have to name it any
or any other name since you are not using it, so you can also just do
Cases[{f[a], 2 f[b]}, _. f[x_] :> x]
(* {a, b} *)
The rules are
Notice that it says x_^n_
does not match 1
for n
. Same thing for the second example.
I also changed ->
to :>
. It is more safe this way. The rule of thumb for this, if x_
or n_
or whatever named pattern is used, shows up on left side then more safe to use :>
to emit it on right side of the rule.
Learned this rule from Power Programming with Mathematica: The Kernel Book by David B. Wagner
page 148, where he gives an example of why this can make difference if delayed version is used or not.
ClearAll[u, y];
expr = Sqrt[u - 1]/Sqrt[u^2 - 1];
expr /. 1/Sqrt[y_] -> 1/Sqrt[Factor[y]]
Compare to what happens when using :>
instead of ->
expr /. 1/Sqrt[y_] :> 1/Sqrt[Factor[y]]
Which is what we wanted. Wagner gives the explanation of the difference as follows
So when in doubt, or if something does not happen the way you expect it, use :>
instead of ->
. In your examples, using ->
or :>
gives same result, since this issue does not show up. But in more complicated cases it can as in the example in the book above.
Here is summary of most important rules from my Mathematica cheat sheet collected from Wolfram help pages
FullForm[1/Sqrt[2]]
if you ever need to pattern match square roots. UsingFullForm[{f^2, g^3, k^p, h}]
andFullForm[{f[a], 2 f[b]}]
will allow you to see what Mathematica sees when it's searching through the expressions. In the first example, you can see that they all havePower
except for the last one. $\endgroup$