String transformation for subject course code for Dart/Flutter


Asked by iqFareez on November 25, 2021 (source).

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.


Question answered by Jahidul I (source).

You can achieve the desired behaviour by using regular expressions:

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

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

Note: This will produce the same result, regardless of how many whitespaces your user enters between the characters and numbers.

Video Answers on YouTube