Search code examples
stringfluttertextnumbersnewline

Insert new line in string when number with a dot appears in flutter


I have different text's that look like the following:

"1. do some whatever. 2. Whatever you do. 3. Idk.

I want to insert a new line before a number followed by a dot appears.

How can i do that?


Solution

  • If you have a String and want to manually insert new lines you can just use the \n character which is a new line.

    "1. do some whatever.\n2. Whatever you do.\n3. Idk."

    On the other hand, if you want to do it programmatically, you need to look a RegExp Something like the following could fit your scenario, it check all number + dot and add a \n before it but not the first one.

    String addNewLineBeforeNumber(String input) {
      return input.replaceAllMapped(
          RegExp(r'(?<!^)(\d+\.)'), (match) => '\n${match.group(0)}');
    }