Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart/Flutter: Split string every nth character?

I have a single string made up of two digit numbers with leading zeros (ie '0102031522')

that I want to split into a list as integers without the leading zeros.

Output of this example should be [1,2,3,15,22].

I'm having trouble trying to get this converted as Dart is new to me, and i have no clue where to start. Any suggestions?

like image 633
Michael Avatar asked Aug 31 '26 05:08

Michael


1 Answers

For any size split and making a list.

void main() {
  final splitSize = 2;
  RegExp exp = new RegExp(r"\d{"+"$splitSize"+"}");
  String str = "0102031522";
  Iterable<Match> matches = exp.allMatches(str);
  var list = matches.map((m) => int.tryParse(m.group(0)));
  print(list);
}

Tested on dartpad

like image 77
Doc Avatar answered Sep 03 '26 04:09

Doc