# How to replace plus sign by comma

I want to replace plus by comma and the order of numbers in the list should be in increasing order. Example:

a1 + a10 + a11 + a13 + a2 + a27 + a28


In this expression, I want to replace plus sign by comma and delete "a". To get a list of numbers and the order should be

{1,2,10,11,13,27,28}


I have tried this, but it's not convenient...

StringReplace["a1 + a 10 + a 11 + a 13 + a2 + a27 + a28" , "+ a" -> ","]


Another way:

expr = a1 + a10 + a11 + a13 + a2 + a27 + a28;

ToExpression@StringDrop[ToString[#], 1] & /@ List @@ expr

(* ==> {1, 10, 11, 13, 2, 27, 28} *)


You can then Sort them.

Another option:

Block[
{Plus = Function[Sort@ToExpression@StringReplace[ToString[{##}], LetterCharacter -> ""]]},
a1 + a10 + a11 + a13 + a2 + a27 + a28
]
(* {1, 2, 10, 11, 13, 27, 28} *)


Works with other possibilities, such as "b123", "abc123", etc.

expr = a1 + a10 + a11 + a13 + a2 + a27 + a28


Then:

expr /. Plus -> List // ToString /@ # & // StringReplace[#, "a" -> ""] & // ToExpression // Sort


Gives:

{1, 2, 10, 11, 13, 27, 28}

Yet another way:

Sort @ ToExpression @
StringCases[ToString[a1 + a10 + a11 + a13 + a2 + a27 + a28],
DigitCharacter ..]

• NumberString will do too. +1. – Kuba Jan 23 '14 at 23:41
• I just realized that my answer duplicates yours. I hope my use of DigitQ and FromDigits is sufficient to justify the existence. If you disagree I'll delete mine and add that variant to yours. – Mr.Wizard Jan 25 '14 at 0:57
• @Mr.Wizard I don't have a problem with it. Thanks for asking. – Michael E2 Jan 25 '14 at 1:45

The following employs only 3 functions. (I assume the input is a string.)

Sort@ToExpression@StringSplit[t, {" + a", "a"}]


Another formulation:

expr = a1 + a10 + a11 + a13 + a2 + a27 + a28;

FromDigits /@ StringCases[ToString @ expr, __?DigitQ] // Sort

{1, 2, 10, 11, 13, 27, 28}


Just a thought here because the question has already been answered well. But If you had the option of generating that equation then your variables are named in an awkward way. It would be much easier if you had used subscripts.

$eqn= a_1+a_{10}+a_{11}+a_{13}+a_2+a_{27}+a_{28}$

Then you could have done something like this:

List @@ eqn /. Subscript[a, c_] -> c

• There are other options such as down-values as well... however, using subscripts opens a whole new can of worms, especially with assigning definitions and clearing them :) – rm -rf Jan 26 '14 at 23:59

Inspired by @R.M.'s answer, here is another way to temporarily define Plus:

Block[{Plus = Sort[FromDigits@StringDrop[SymbolName@#, 1] & /@ {##}] &}, expr]


{1, 2, 10, 11, 13, 27, 28}