Search code examples
stringflutterdartsplit

Dart/Flutter: Split string before last character


I have a single string made up of numbers of varying lengths, example: "12345"

I would like to break the String before the last character, so that I have ["1234", "5"]

I can do this with substring, but I would like a more simplified way, like using split(), but I don't know how

Below, example using substring:

 String numbers = '123456';
 var partOne = numbers.substring(0, numbers.length -1);
 var partTwo = numbers.substring(numbers.length -1, numbers.length);
 print('partOne $partOne - partTwo $partTwo'); // partOne 12345 - part Two 6

Solution

  • void main(List<String> arguments) {
      const numbers = '123456';
      final re = RegExp('(.*)(.)');
      final match = re.firstMatch(numbers);
      if (match != null) {
        print(match.group(1));
        print(match.group(2));
      }
    }