Search code examples
regexdartwhitespace

Dart: Use regexp to remove whitespaces from string


I am attempting to remove all white spaces from a string using Dart and Regexp. Given the following string: "test test1 test2" I would want to get: "testtest1test2". I have read some examples in javascript but they do not seem to work in Dart. These are some attempts so far:

print("test test1 test2".replaceAll(new RegExp(r"/^\s+|\s+$|\s+(?=\s)/g"), ""));
print("test test1 test2".replaceAll(new RegExp(r"/\s+\b|\b\s/ig"), ""));

This is based off: Regex to remove whitespaces

Can someone advise where I am going wrong with this.


Solution

  • I think this covers more bases: textWithWhitespace.replaceAll(new RegExp(r"\s+\b|\b\s|\s|\b"), "")

    The current accepted answer was not working for me. In the case where it was all whitespace, my whitespace was not removed

    String whitespace = "    ";
    print(whitespace.replaceAll(new RegExp(r"\s\b|\b\s"), "").length);
    //length is 4 here