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.

1
  • 6
    I think if you simply want to remove all whitespace it should be: print("test test1 test2".replaceAll(new RegExp(r"\s+"), "")); Commented Aug 24, 2017 at 15:55

9 Answers 9

16

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
Sign up to request clarification or add additional context in comments.

Comments

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("");

1 Comment

This removes spaces and not all whitespaces. It may also be a costly performance wise, although I have not given it a fair testing.
5
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

Comments

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)

3 Comments

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"
I assume what sniperd posted below your question should do what you want.
@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"), ""));
4

This works fine even without using RegExp:

myString.replaceAll(" ", "");

Comments

1

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

Comments

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
}

Comments

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+'), ' ');

Comments

-2

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

1 Comment

This will only remove preceding and trailing whitespaces though. Not anything in the middle of the string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.