Search code examples
stringdartreplaceall

How to replace all characters in a string in Dart except the space character


String text = "replace all characters" --> 22 characters

text.replaceAll(RegExp('.'), '*');   

// result -> ********************** --> 22 characters

In this way, all characters change. How do I exclude the space character.

// I want it this

// result -> ******* *** ********** -> Characters 8 and 13 are empty.

Solution

  • What you want is a negative match:

    void main() {
      String text = "replace all characters";
      print(text.replaceAll(RegExp('[^ ]'), '*'));
      // ******* *** **********
    }
    

    [^ ]Will match any character that is not space.