Home > Software design >  In Flutter/Dart, how to separate between alphabeth and numeric in a single string into array?
In Flutter/Dart, how to separate between alphabeth and numeric in a single string into array?

Time:01-08

For example:

  • "X84J25" --> <dynamic>[ "X", 84, "J", 25 ]
  • "96KGWWA3" --> <dynamic> [ 96, "KGWWA", 3 ]
  • "L8273BB" --> <dynamic> [ "L", 8273, "BB" ]
  • "C" --> <dynamic> [ "C" ]
  • "92123" --> <dynamic> [ 92123 ]

This is sort of function split, but while split has a clear separator defined (like space for example), this is separated by flip flop between alphabet to numeric to alphabet again.

CodePudding user response:

Split does not really work here but you can do something like this instead using a regular expression to capture multiple matches in your string input:

void main() {
  print(weirdSplit("X84J25")); // [X, 84, J, 25]
  print(weirdSplit("X84J25").map((dynamic e) => e.runtimeType));
  // (String, int, String, int)

  print(weirdSplit("96KGWWA3")); // [96, KGWWA, 3]
  print(weirdSplit("L8273BB")); // [L, 8273, BB]
  print(weirdSplit("C")); // [C]
  print(weirdSplit("92123")); // [92123]
}

List<dynamic> weirdSplit(String input) => <dynamic>[
      ...RegExp(r'\d |\D ')
          .allMatches(input)
          .map((match) => match[0]!)
          .map((string) => int.tryParse(string) ?? string)
    ];
  •  Tags:  
  • Related