Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Any idea which Cases statement will work for both A^2 and CA^4X^36 to find the powers? If I set sym to these two expressions, one requires a curly brackets around the first argument and the other doesn't.

(* Sample 1.  Returns {} *)
Clear[x]; Clear[y];
sym = "A^2";
Cases[ToExpression[sym], x_^y_ -> {x, y}]

(* Sample 2. Returns {{CA,4},{X,36}} - as required*)
Clear[x]; Clear[y];
sym = "CA^4X^36";
Cases[ToExpression[sym], x_^y_ -> {x, y}]

(* Sample 3. Placing brackets around the first argument of the Cases \
function returns {{A,2}}  - as required *)
Clear[x]; Clear[y];
sym = "A^2";
Cases[{ToExpression[sym]}, x_^y_ -> {x, y}]
share|improve this question
You're not finding powers within strings because you convert the strings to expressions before finding powers. Since Cases looks for matches among parts of the input (either a list or an expression), it will not find a match in the expression A^2. Its only parts are A and 2. You can look at FullForm[ToExpression[sym]] to see its structure and confirm what its parts look like. That's why you need {A^2} to make A^2 a part of the input expression for Cases. So you may want to use that {...} wrapper with the other examples too and append , Infinity] to Cases[.... – Jens Jun 5 '13 at 5:02
I think that if you take a look at Cases in the documentation center, under the section heading Scope that the fifth example may be what you are looking for. – Clif Jun 5 '13 at 5:27
up vote 5 down vote accepted

Changing the level specifications is what you need here:

Cases[ToExpression["a^2"], x_^y_ :> {x, y}, {0, ∞}]
   {{a, 2}}

Cases[ToExpression["CA^4X^36"], x_^y_ :> {x, y}, {0, ∞}]
   {{CA, 4}, {X, 36}}

Nevertheless, you might want to consider manipulating the strings directly:

StringCases["a^2", RegularExpression["(\\w+)\\^(\\d+)"] -> {"$1", "$2"}]
   {{"a", "2"}}

StringCases["CA^4X^36", RegularExpression["(\\w+)\\^(\\d+)"] -> {"$1", "$2"}]
   {{"CA", "4"}, {"X", "36"}}
share|improve this answer
Thanks - I spent ages trying to work that out! – MLD Jun 5 '13 at 6:15
@MLD Note that J. M. used :> (RuleDelayed) rather than ->; by doing so x and y are localized and you will not need to use Clear on these symbols. – Mr.Wizard Jun 5 '13 at 6:50
@Mr.Wizard I hadn't noticed that and thank-you for pointing it out. – MLD Jun 6 '13 at 7:00

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.