Dart: Use regexp to remove whitespaces from string

2019-07-14 17:03发布

问题:

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.

回答1:

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


回答2:

print("test test1 test2".replaceAll(new RegExp(r"\s+\b|\b\s"), ""));

(without /ig) worked for me. These options are not supported in Dart this way.

  • /g is equivalent to All in replaceAll
  • /i is equivalent to new RegExp(r"...", caseSensitive: false)


回答3:

I couldn't believe that it was so complex to simply remove whitespaces from a string. So I came up with this solution, which I like much more than playing with regex:

myString.split(" ").join("");


标签: regex dart