String transformation for subject course code for Dart/Flutter

For interaction with an API, I need to pass the course code in <string><space><number> format. For example, MCTE 2333, CCUB 3621, BTE 1021.

Yes, the text part can be 3 or 4 letters.

Most users enter the code without the space, eg: MCTE2333. But that causes error to the API. So how can I add a space between string and numbers so that it follows the correct format.


try with regex

void main() {
  String a = "MCTE2333";

  String aStr = a.replaceAll(new RegExp(r'[^0-9]'), ''); //extract the number
  String bStr = a.replaceAll(new RegExp(r'[^A-Za-z]'), '');//extract the character
  print("$bStr $aStr"); //MCTE 2333 

Try this.You have to give two texfields. One is for name i.e; MCTE and one is for numbers i.e; 1021. (for this textfield you have to change keyboard type only number).

After that you can join those string with space between them and send to your DB. It's just like hack but it will work.


You can use tryParse to check index value type and then parse

main(List<String> args) {
  String data = 'MCTR 2333';

  late String result;

  if (data.contains("")) {
    result = data;
  if (int.tryParse(data[3]) != null) {
    result = data.substring(0, 3) + " " + data.substring(3, data.length);
  } else {
    result = data.substring(0, 4) + " " + data.substring(4, data.length);



Here is the entire logic you need:

void main() {
 String courseCode= "MMM111";
 String parsedCourseCode = "";
 if (courseCode.contains(" ")) {
   parsedCourseCode = courseCode;
 } else {
    var r1 = RegExp(r'[0-9]',   caseSensitive: false);
    var r2 = RegExp(r'[a-z]',   caseSensitive: false);
    var letters = courseCode.split(r1);
    var numbers = courseCode.split(r2);
    parsedCourseCode = "${letters[0].trim()} ${numbers[3]}";

Play around with the input value (courseCode) to test it - also use dart pad if you want. You just have to add this logic to your input value, before submitting / handling the input form of your user :)

Previous : Material UI autocomplete not being recognized
Next : Javascript- How to access specific button