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:
4000123456789010Only 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:
1000000Unicode 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
abcFunctions used in this recipe
- String.replaceAll() — Replaces every match of a regular expression.
- String.replace() — Replaces every occurrence of a substring or a character with another string.
- String.strip() — Removes any Unicode whitespace from both ends of a string.