Try this:

String after = before.trim().replaceAll(" +", " ");

See also

  • String.trim()
    • Returns a copy of the string, with leading and trailing whitespace omitted.
  • regular-expressions.info/Repetition

No trim() regex

It's also possible to do this with just one replaceAll, but this is much less readable than the trim() solution. Nonetheless, it's provided here just to show what regex can do:

    String[] tests = {
        "  x  ",          // [x]
        "  1   2   3  ",  // [1 2 3]
        "",               // []
        "   ",            // []
    };
    for (String test : tests) {
        System.out.format("[%s]%n",
            test.replaceAll("^ +| +$|( )+", "$1")
        );
    }

There are 3 alternates:

  • ^_+ : any sequence of spaces at the beginning of the string
    • Match and replace with $1, which captures the empty string
  • _+$ : any sequence of spaces at the end of the string
    • Match and replace with $1, which captures the empty string
  • (_)+ : any sequence of spaces that matches none of the above, meaning it's in the middle
    • Match and replace with $1, which captures a single space

See also

  • regular-expressions.info/Anchors
Answer from polygenelubricants on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › remove-extra-spaces-string
Remove extra spaces from a string - GeeksforGeeks
December 3, 2023 - "; removeSpaces(ref str); Console.WriteLine(str); } // Function to in-place trim all spaces in the // string such that all words should contain only // a single space between them. public static void removeSpaces(ref string str) { // n is length ...
Discussions

[Java] Removing extra whitespace from a string and counting words in a string?
look into trim() and split() methods. More on reddit.com
🌐 r/learnprogramming
11
7
February 22, 2012
Ways to remove spaces from a string using JavaScript
Thanks for sharing. I just did a performance test. The average time it takes each function (10,000 runs) to remove the spaces from a text with 1800 words/spaces in it. replaceAll: 0.08585000002384185 miliseconds replace: 0.10449000005722046 miliseconds splitAndJoin: 0.2322219943579563 miliseconds filterAndJoin: 1.1504000001549721 miliseconds Seems like replaceAll is the fastest and filterAndJoin is the slowest. More on reddit.com
🌐 r/learnjavascript
33
204
January 11, 2023
People also ask

How to remove all spaces from a string in Java?
If you want to remove every space in a Java string, use replace(" ", ""). This method only removes space characters, so tabs and newlines will remain. It’s useful when formatting strings like phone numbers or IDs without extra characters.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › removing whitespace from string in java
Efficient String Manipulation: Removing Whitespace in Java
How can I remove all whitespace from a Java string using Java Streams?
Using Java 8+ Streams, convert the string to a character stream and filter out whitespace with Character.isWhitespace(c). Then collect the result into a new string. This method is clean, modern, and useful for more functional programming styles.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › removing whitespace from string in java
Efficient String Manipulation: Removing Whitespace in Java
How to remove whitespace from the beginning and end of a string in Java?
To remove whitespace from both ends of a string in Java, use the trim() method. It eliminates leading and trailing spaces but does not affect spaces in between. This is ideal when cleaning up user inputs or text from external sources.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › removing whitespace from string in java
Efficient String Manipulation: Removing Whitespace in Java
🌐
Medium
medium.com › @AlexanderObregon › trimming-extra-spaces-from-text-in-java-b20af8a84b6d
Trimming Extra Spaces from Text in Java | Medium
July 30, 2025 - Java’s replaceAll() method can take a pattern that matches any group of one or more whitespace characters and replace it with something cleaner, like a single space. This works well when your input has unpredictable spacing between words.
🌐
Reddit
reddit.com › r/learnprogramming › [java] removing extra whitespace from a string and counting words in a string?
r/learnprogramming on Reddit: [Java] Removing extra whitespace from a string and counting words in a string?
February 22, 2012 -

Hello all,
I am a college student taking my first programming class, and need help with some parts of an assignment, and was hoping I could get some help here. In the program we're writing, the user is prompted for a string, and then we must delete all extra whitespace between the words (so no trim), as well as making sure the sentence meets the minimum word count.

Here is what I have written for the word counter, but it seems really bulky, and it also doesn't count words if they are proceeded by a comma or other (valid) non-letter character:

//Error for a sentence with too few words.
int wordCountStart = 0;
int wordCount = 1;
char b = sentence.charAt(wordCountStart);
while (wordCountStart < sentence.length())
{
  while ((b == ' ') || (b == '(') || (b == ')') || (b == '.') || (b == '?') || (b == '!') || (b == ',') || (b == '/') || (b == '"') || (b == '[') || (b == ']') || (b == '-') || (b == ':') || (b == ';') ||(b == '\''))
  {
    wordCountStart ++;
    if (wordCountStart == sentence.length()) break;
    b = sentence.charAt(wordCountStart);
  }
  while (Character.isLetter(b))
  {
    wordCountStart ++;
    if (wordCountStart == sentence.length()) break;
    b = sentence.charAt(wordCountStart);
  }
  if (b == ' ')
  {
    wordCount ++;
  }
  
}
if (wordCount < 7)
{
  JOptionPane.showMessageDialog(null, "Your sentence needs to contain at least 7 words.", "Error", JOptionPane.ERROR_MESSAGE);
  System.exit(0);
}
🌐
How to do in Java
howtodoinjava.com › home › string › java – normalize extra white spaces in a string
Java - Normalize Extra White Spaces in a String - HowToDoInJava
January 6, 2023 - using trim(String) to remove leading and trailing whitespace, and then · replacing sequences of whitespace characters with a single space · Add the latest version of commons-lang3 from Maven repo.
🌐
Coderanch
coderanch.com › t › 511808 › java › remove-multiple-spaces-words-leave
How to remove multiple spaces between words and leave 1 space between (Beginning Java forum at Coderanch)
September 28, 2010 - Here is a tutorial of regular expressions: http://download.oracle.com/javase/tutorial/essential/regex/index.html ... This is what I tried and it works as expect! Thank you very much String str = "AB E LINCOLN"; //where there are 2 or more spaces between String regex = "\\s{2,}"; str = str.replaceAll(regex, " "); result in str = ABE LINCOLN
Find elsewhere
🌐
Sololearn
sololearn.com › en › Discuss › 2176162 › how-can-i-remove-extra-spaces-of-a-string-in-java
How can I remove extra spaces of a string in java?
February 20, 2020 - Sololearn is the world's largest community of people learning to code. With over 25 programming courses, choose from thousands of topics to learn how to code, brush up your programming knowledge, upskill your technical ability, or stay informed about the latest trends.
🌐
Baeldung
baeldung.com › home › java › java string › remove whitespace from a string in java
Remove Whitespace From a String in Java | Baeldung
August 13, 2024 - Usually, when we need to deal with a string like myString in Java, we often face these two requirements: removing all whitespace characters from the given string -> “IamawonderfulString!” · replacing consecutive whitespace characters with a single space, and removing all leading and trailing whitespace characters -> “I am a wonderful String !”
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › removing whitespace from string in java
Efficient String Manipulation: Removing Whitespace in Java
June 25, 2025 - To remove every whitespace character—including tabs (\t), spaces, and newlines—from a Java string, apply replaceAll("\\s", ""). This is especially useful when cleaning input data for validation, encryption, or transmission where extra characters ...
🌐
Programiz
programiz.com › java-programming › examples › remove-whitespaces
Java Program to Remove All Whitespaces from a String
import java.util.Scanner; class Main { public static void main(String[] args) { // create an object of Scanner Scanner sc = new Scanner(System.in); System.out.println("Enter the string"); // take the input String input = sc.nextLine(); System.out.println("Original String: " + input); // remove white spaces input = input.replaceAll("\\s", ""); System.out.println("Final String: " + input); sc.close(); } }
🌐
Quora
quora.com › How-do-you-remove-special-and-space-characters-in-Java
How to remove special and space characters in Java - Quora
Answer: Java uses replaceAll() method. This method replaces each substring matching the given regular expression with the given replacement. A String strInput example shows this. Java uses String trim() method. This method removes leading and trailing whitespaces. This whitespace character unicod...
🌐
regex101
regex101.com › library
regex101: Community Pattern Library
Ex: test@example.pt -> extract 'example.pt'Submitted by Fnxk ... http://stackoverflow.com/questions/2362985/verifying-a-cron-expression-is-valid-in-javaSubmitted by anonymous ... RegEx email /^((?!\.)[\w-_.]*)(@\w+)(\.\w+(\.\w+)?)$/gim; Just playing with Reg Ex. This to validate emails in following ways The email couldn't start or finish with a dot The email shouldn't contain spaces into the string The email shouldn't contain special chars ( mailname@domain.com First group takes the first string with the name of email \$1 => (mailname) Second group takes the @ plus the domain: \$2 => (@domain) Third group takes the last part after the domain : \$3 => (.com) Submitted by https://www.linkedin.com/in/peralta-steve-atileon/
🌐
Medium
rameshfadatare.medium.com › java-program-to-remove-all-whitespace-from-a-string-819ccfb84997
Java Program to Remove All Whitespace from a String | by Ramesh Fadatare | Medium
December 13, 2024 - The replaceAll() method is used with the regular expression \\s to match all whitespace characters (spaces, tabs, newlines, etc.) and replace them with an empty string "". The program prints the string without any whitespace using ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › removing-whitespaces-using-regex-in-java
Removing whitespaces using Regex in Java - GeeksforGeeks
July 11, 2025 - The java.util.regex.Matcher.replaceAll(String replacement) method replaces every subsequence of the input sequence that matches the pattern with the given replacement string. ... Parameters: replacement - The replacement string.
🌐
Git
git-scm.com › docs › gitignore
Git - gitignore Documentation
If one wants to restrict this only to the directory and not in its subdirectories, one can prepend the pattern with a slash, i.e. /hello.*; the pattern now matches hello.txt, hello.c but not a/hello.java. The pattern foo/ will match a directory foo and paths underneath it, but will not match a regular file or a symbolic link foo (this is consistent with the way how pathspec works in general in Git) The pattern doc/frotz and /doc/frotz have the same effect in any .gitignore file. In other words, a leading slash is not relevant if there is already a middle slash in the pattern.
🌐
Automationtesting
automationtesting.in › home › how to remove whitespaces from a string in java
How to Remove Whitespaces from a String in Java-Selenium Webdriver Appium Complete Tutorial
November 16, 2019 - public class RemoveWhitespacesString { public static void main(String[] args) { String str = "Java is a programming language"; char ch [] = str.toCharArray(); String str2 = ""; for(int i=0; i<ch.length; i++) { if(ch[i]!=' ') { str2 = str2 + ch[i]; } } System.out.println(str2); } }
🌐
LabEx
labex.io › tutorials › java-how-to-remove-whitespaces-from-a-string-in-java-11-414125
How to remove whitespaces from a string in Java 11 | LabEx
In this tutorial, we'll explore the different ways to remove whitespaces from a string in Java 11, covering both the built-in methods and some common use cases. In Java, a string is an immutable sequence of characters. This means that once a string is created, its value cannot be changed. If you need to modify a string, you'll need to create a new string object with the desired changes. Java 11 provides a wide range of methods and classes for working with strings, including:
🌐
GeeksforGeeks
geeksforgeeks.org › java › trim-remove-leading-trailing-spaces-string-java
Java Program to Trim Leading and Trailing Spaces from a String - GeeksforGeeks
July 23, 2025 - // Java program to remove leading and trailing spaces // using the trim() method public class RemoveSpaces { public static void main(String args[]) { String s1 = " Hello World "; System.out.println(s1); System.out.println(s1.trim()); String ...
🌐
Visual Studio Code
code.visualstudio.com › docs › getstarted › tips-and-tricks
Visual Studio Code tips and tricks
November 3, 2021 - { "env": { "browser": true, "commonjs": true, "es6": true, "node": true }, "parserOptions": { "ecmaVersion": 6, "sourceType": "module", "ecmaFeatures": { "jsx": true, "classes": true, "defaultParams": true } }, "rules": { "no-const-assign": 1, "no-extra-semi": 0, "semi": 0, "no-fallthrough": 0, "no-empty": 0, "no-mixed-spaces-and-tabs": 0, "no-redeclare": 0, "no-this-before-super": 1, "no-undef": 1, "no-unreachable": 1, "no-use-before-define": 0, "constructor-super": 1, "curly": 0, "eqeqeq": 0, "func-names": 0, "valid-typeof": 1 } }