Home > database >  Split String after first occurrence of number(Flutter)
Split String after first occurrence of number(Flutter)

Time:09-20

I have a string which is having text and numbers. I want to split the string based on the first occurrence of number in that string

Eg: "Hello World 2022 September 19"

Expected result will be [Hello World,2022 September 19]

CodePudding user response:

you can try this:

String string = "Hello World 2022 September 19";
final split = string.split(RegExp(' (?=\\d)'));
final result = [split[0], split.skip(1).join(' ')];
print(result);

CodePudding user response:

There are multiple ways to do it. but i think the fastest and easiest way is to use replaceFirstMapped.

final str = 'Hello World 2022 September 19';

// There is a space added in front of number([0-9]) includes the space before number(' 2').
final regx = RegExp(r" [0-9]");

// Replace the first occurrence of from in this string.
final strResult = str.replaceFirstMapped(regx, (Match m) => ',${m[0]}');

// Result
print(strResult);

check this out for more info:
https://api.dart.dev/stable/2.18.1/dart-core/String/replaceFirstMapped.html

  • Related