How do I split a String of nine characteres with a regular expression in Dart?
623
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]}-');
}
Author by
Pedro Massango
Associate Android Developer | Kotlin | Dart | Android Studio | Flutter | Youtuber | Content Writer
Updated on December 12, 2022Comments
-
Pedro Massango over 1 year
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.
-
BambinoUA almost 5 yearsAs for me this regexp does not match the last 3 digits.
-
BambinoUA almost 5 yearsOk. I just tested the regular expression here regex101.com and I saw unexpected results.
-
Pedro Massango almost 5 yearsThis one seems the best option. Thank you @Eugene.