Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to remove all whitespace from a string

Short answer

The regular expression \\s matches any whitespace character — replace it with an empty string:

void main() {
    String card = " 4000 1234\t5678 9010\n";
    IO.println(card.replaceAll("\\s", ""));
}

Output:

4000123456789010

Only regular spaces

If you only need to remove the space character, you do not need a regular expression — replace() is enough:

void main() {
    IO.println("1 000 000".replace(" ", ""));
}

Output:

1000000

Unicode spaces

\\s does not match the non-breaking space  , which often comes from HTML and spreadsheets. Use the \\p{Z} class together with \\s:

void main() {
    String price = "1 250 €";
 
    IO.println(price.replaceAll("\\s", ""));
    IO.println(price.replaceAll("[\\s\\p{Z}]", ""));
}

Output:

1 250€
1250€

Common mistake

Passing a regular expression to replace(). replace() searches for literal text, so "\\s" finds nothing there:

void main() {
    IO.println("a b c".replace("\\s", ""));
    IO.println("a b c".replaceAll("\\s", ""));
}

Output:

a b c
abc

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.