# Given an expression using kets, such as '|2> + 4|3>+…,' find the largest ket index in a ket?

I have some expressions containing Kets, like

|1> + Sqrt[6] |3>


where the kets are created using [esc]ket[esc]. How can I find the largest number inside a ket? For example I would expect:

LargestN[|1> + Sqrt[6] |3>] = 3


At the moment I am doing it through matching regular expressions in the FullForm:

LargestN[state_] := Max[ToExpression /@ (StringReplace[#,
RegularExpression@"\\D" -> ""] & /@
StringCases[state // FullForm // ToString,
RegularExpression@"Operator$ket, \\d+$"])]


While this does work, does anyone know a nicer way to do this?

Edit: Just in case someone stumbles across this in the future and gets confused, my code above won't work for you as I had another package loaded that was causing kets to be represented as

Operator[ket, n]


rather than the conventional

Ket[n]


expr= Ket[1] + Sqrt[6] Ket[3]

3
• @RuviLecamwasam Of course, this should work also if you use the form Operator[ket,n] but you have to replace Ket[a_]->a with Operator[ket,a_]->a. – SquareOne Oct 15 '15 at 12:23