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}]
  • 1
    $\begingroup$ 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[.... $\endgroup$ – Jens Jun 5 '13 at 5:02
  • $\begingroup$ 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. $\endgroup$ – Clif Jun 5 '13 at 5:27

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"}}
  • $\begingroup$ Thanks - I spent ages trying to work that out! $\endgroup$ – MLD Jun 5 '13 at 6:15
  • $\begingroup$ @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. $\endgroup$ – Mr.Wizard Jun 5 '13 at 6:50
  • $\begingroup$ @Mr.Wizard I hadn't noticed that and thank-you for pointing it out. $\endgroup$ – MLD Jun 6 '13 at 7:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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