How do I split a String of nine characteres with a regular expression in Dart?

Viewed 712

I have a String called pin with a value like: 123456789 and I need to do the following:

What I have:

String pin = "123456789";

What I want after the operation:

String result = "123-456-789";

what I'm doing right now:

  String _formatReferenceCode(String code){
    final list = code.split("");
    String part1 = list.sublist(0, 3).join();
    String part2 = list.sublist(3, 6).join();
    String part3 = list.sublist(6, 9).join();
    return "$part1-$part2-$part3";
  }

String result = _formatReferenceCode(referenceCode);

// it prints: "123-456-789"

My current code works, but I want to know if there is a better way to do this. Thank you in advanced.

2 Answers

as an option you can use regexp negative lookahead

  String _formatReferenceCode(String code) {
    final Pattern pattern = RegExp(r'(.{3})(?!$)');
    return code.replaceAllMapped(pattern, (m) => '${m[0]}-');
  }

You should use the power of regular expressions and method replaceAllMapped of String class

final pin = '123456789';
// Divide PIN by 3 digits (\d{3}) and place result to match group
final regexp = RegExp(r'(\d{3})(\d{3})(\d{3})');
// Call method which returns substitution
final result = pin.replaceAllMapped(
    regexp, (match) => '${match[1]}-${match[2]}-${match[3]}');
Related