11

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.

SSS
  • 761
  • 2
  • 9
  • 19
  • 6
    I think if you simply want to remove all whitespace it should be: print("test test1 test2".replaceAll(new RegExp(r"\s+"), "")); – sniperd Aug 24 '17 at 15:55

9 Answers9

15

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
Erik B
  • 198
  • 2
  • 6
9

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("");
Robouste
  • 3,020
  • 4
  • 33
  • 55
  • This removes spaces and not all whitespaces. It may also be a costly performance wise, although I have not given it a fair testing. – Shaun Ramsey Mar 12 '23 at 18:13
4
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)
lrn
  • 64,680
  • 7
  • 105
  • 121
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thanks - that explains what I was doing wrong! I see this works just for single space gaps - do you know what I should add to make it work for varying length space gaps? e.g. "test test1 test2" – SSS Aug 24 '17 at 16:14
  • I assume what sniperd posted below your question should do what you want. – Günter Zöchbauer Aug 24 '17 at 16:16
  • @GünterZöchbauer check this.. this is not work this is not work.. try this one `String name = '4 ever 1 k g @@ @'; print(name.replaceAll(new RegExp(r"\s+\b|\b\s"), ""));` – BIS Tech May 04 '20 at 17:59
4
str.replaceAll(new RegExp("[ \n\t\r\f]"), '');

This removes all whitespace (\t \r \n \f) which matches a space, a tab, a carriage return, a line feed or a form feed as seen here https://www.regular-expressions.info/shorthand.html#:~:text=%5Cs%5Cd%20matches%20a%20whitespace,latter%20matches%201%20(one)

String s1 = " have Yourself \n \t A M e r\r \r \f r   y  Little Christma s    ";
print(s1.replaceAll(new RegExp("[ \n\t\r\f]"), '')); 
//haveYourselfAMerryLittleChristmas

The second example demonstrates that a string which is all whitespace has length zero after applying the replaceAll.

String whiteSpacesOnly = "   \t \n \r \f";
print(whiteSpacesOnly.replaceAll(new RegExp("[ \n\t\r\f]"), '').length); 
//0
3

This works fine even without using RegExp:

myString.replaceAll(" ", "");
intraector
  • 994
  • 10
  • 20
1

whitespace.replaceAll(new RegExp(r"\ "), ""); This is ok for me.

H Zan
  • 359
  • 1
  • 4
  • 16
1

This isn't an exact answer to the question. However, it's the answer I needed when I stumbled upon this problem earlier today.

The following code converts a String with random spaces (even multiple spaces) all throughout it to a String that only has single spaces between each word (it removes spaces on the outsides too).

For example, this could be good for when your user chooses a username for your application and decides to be a goof and enters " Mr Bob Felix Johnson " instead of "Mr Bob Felix Johnson".

void main() {
  // INPUT NAME WITH UNWANTED SPACES
  String text = '  Mr  Bob Felix    Johnson     ';
  // INPUT NAME WITH UNWANTED SPACES
  final pattern = RegExp('\\s+');
  text = text.replaceAll(pattern, ' ');
  if (text[0] == ' ') {
    text = text.substring(1, text.length);
  }
  if (text[text.length - 1] == ' ') {
    text = text.substring(0, text.length - 1);
  }
  // NAME WITH REMOVED SPACES
  print(text); // THIS PRINTS "Mr Bob Felix Johnson"
  // NAME WITH REMOVED SPACES
}
Matthew Trent
  • 2,611
  • 1
  • 17
  • 30
0

In addition to Matthew Trent's solution here https://stackoverflow.com/a/67396167/12411655

Instead of this

if (text[0] == ' ') {
    text = text.substring(1, text.length);
  }
  if (text[text.length - 1] == ' ') {
    text = text.substring(0, text.length - 1);
  }

you can just use trim() method like this

text.trim().replaceAll(RegExp('\\s+'), ' ');
-2

mysecond = myString.trim() works for me :)

  • 2
    This will only remove preceding and trailing whitespaces though. Not anything in the middle of the string – Suraj Rao Dec 03 '21 at 14:31