Skip to main content

algorithm - Splitting strings into letter keys and integers



I have strings of the following form:


string = "ABC123DEFG456HI89UZXX1";

Letter keys of variable lengths are followed by (positive) integers.


I want to get this transformation:



{{"ABC", 123}, {"DEFG", 456}, {"HI", 89}, {"UZXX", 1}}



I have written:


chars = Characters @ string;


runs = Length /@ Split[IntegerQ @ ToExpression @ # & /@ chars]


{3, 3, 4, 3, 2, 2, 4, 1}



takes = Transpose[{# - runs + 1, #}] & [Accumulate @ runs]


{{1, 3}, {4, 6}, {7, 10}, {11, 13}, {14, 15}, {16, 17}, {18, 21}, {22, 22}}




 result =
Partition[StringJoin /@ Map[Take[chars, #] &, takes], 2] /.
{a_String, b_String} :> {a, ToExpression @ b}


{{"ABC", 123}, {"DEFG", 456}, {"HI", 89}, {"UZXX", 1}}



I have two questions:


(1) How could the above coding be shortened / improved? (it seems to be too long for such a trivial problem)



(2) How would a "direct" method (StringCases , StringSplit ...) look like?



Answer



You asked for shortened, improved, so here it is using RegularExpressions:


StringCases[string, RegularExpression["(\\D+)(\\d+)"] :> {"$1", ToExpression["$2"]}]


{{"ABC", 123}, {"DEFG", 456}, {"HI", 89}, {"UZXX", 1}}

Here's a version using StringSplit:


Partition[StringSplit[string, RegularExpression["(\\d+)"] :> FromDigits @ "$1"], 2]

Comments