2

I'm trying to split a string into parts of length 4 in Dart/Flutter.

The best way to do this is by using a regular expression if I'm not wrong. Based on my regex knowledge and digging around I've settled on this regex /.{1,4}(?=(.{4})+(?!.))|.{1,4}$/g. However, I can't figure out how to use it in dart

Here's what I have so far.

String cardNum = "4444444444444444";
List<String> cardNums=cardNum.split(
        RegExp(r".{1,4}(?=(.{4})+(?!.))|.{1,4}$"));

I've already tested regexr

I expect cardNums to be ["4444","4444","4444","4444"]

Instead I'm getting [, , , , ]

Newton Munene
  • 145
  • 3
  • 12
  • Don't you want to *match*? Use `.allMatches` – Wiktor Stribiżew Jul 12 '19 at 12:41
  • 2
    Why reopen? Don't `RegExp rx = new RegExp(r".{1,4}(?=(.{4})+(?!.))|.{1,4}$");` and then `rx.allMatches(cardNum).map((m) => m.group(0))` solve the issue? Of course, you may streamline the pattern (like replace `(?!.)` with `$`) further, but the point is you need to match, not split. – Wiktor Stribiżew Jul 12 '19 at 12:55

0 Answers0