In this Java tutorial, you will learn how to replace multiple spaces with a single space using the String.replaceAll() method and a regular expression, with examples for regular spaces and other whitespace characters.

Replace multiple spaces with a single space in Java

To replace consecutive spaces with one space in Java, call replaceAll() on the string and use a regular expression that matches a sequence of spaces. Replace every matched sequence with " ", a single space.

For example, the expression "[ ]+" matches one or more ordinary space characters:

</>
Copy
String result = text.replaceAll("[ ]+", " ");

This approach is useful when the requirement is specifically to collapse repeated regular spaces between words without treating tabs or line breaks as spaces.

Java replaceAll() pattern for consecutive spaces

The replaceAll() method accepts a regular expression as its first argument and the replacement text as its second argument.

</>
Copy
string.replaceAll(regex, replacement)

For this task, [ ]+ can be read as follows:

  • [ ] matches an ordinary space character.
  • + means one or more occurrences of the preceding pattern.
  • " " is the single space used as the replacement.

Therefore, a sequence containing one, two, three, or more adjacent spaces is replaced by exactly one space.

Example: replace multiple spaces with one space

In this example, we initialize a string that contains multiple spaces coming next to other spaces. We use regex to match multiple (two or more) spaces and then replace them with a single space.

Example.java

</>
Copy
public class Example {
	public static void main(String[] args) {
		String str1 = "Hi!   Good      morning. Have a      good   day.";
		
		//replace one or more spaces with one space
		String resultStr = str1.replaceAll("[ ]+", " ");
		
		System.out.print(resultStr);
	}
}

The string "[ ]+" is a regular expression that matches one or more adjacent regular space characters. Each complete sequence of matching spaces is replaced with a single space.

Run the program. The output shall be as shown below in the console window.

Output

Hi! Good morning. Have a good day.

Replace two or more spaces while leaving single spaces unchanged

If you want the regular expression to match only sequences containing at least two spaces, use [ ]{2,}. Existing single spaces do not match this pattern and are therefore left unchanged.

</>
Copy
public class Example {
    public static void main(String[] args) {
        String text = "Java   makes  string processing easy.";
        String result = text.replaceAll("[ ]{2,}", " ");

        System.out.println(result);
    }
}

Output

Java makes string processing easy.

For the final result, both [ ]+ and [ ]{2,} produce one space between the words in examples like these. The difference is that [ ]+ also matches existing single spaces, while [ ]{2,} matches only runs of two or more spaces.

Use \s+ when tabs and other whitespace should also become one space

The pattern [ ]+ targets ordinary space characters. If the input may also contain tabs, line breaks, or other characters matched by Java regex whitespace shorthand, you can use \s+ instead.

Because a backslash must be escaped inside a Java string literal, the Java source code contains "\\s+".

</>
Copy
public class Example {
    public static void main(String[] args) {
        String text = "Java\tString   example";
        String result = text.replaceAll("\\s+", " ");

        System.out.println(result);
    }
}

Output

Java String example

Choose the pattern based on what you want to normalize. Use [ ]+ when only ordinary spaces should be collapsed. Use \s+ when whitespace such as tabs should also be converted to a space.

Remove leading and trailing spaces while normalizing spaces between words

Replacing repeated spaces does not necessarily remove a single space at the beginning or end of the string. If you also need to remove surrounding whitespace, trim the result.

</>
Copy
public class Example {
    public static void main(String[] args) {
        String text = "   Hello     Java   ";
        String result = text.replaceAll("[ ]+", " ").trim();

        System.out.println(result);
    }
}

Output

Hello Java

Here, replaceAll() collapses the repeated ordinary spaces, and trim() removes leading and trailing characters whose code points are less than or equal to the space character. If your application needs Unicode-aware removal of surrounding whitespace, Java 11 and later also provide strip().

replace() versus replaceAll() for multiple spaces in Java

String.replace() performs literal replacement. It does not interpret its argument as a regular expression. As a result, a call such as replace(" ", " ") only searches for that particular literal sequence and is not a general way to express an arbitrary run of spaces.

String.replaceAll(), on the other hand, accepts a regular expression. This makes patterns such as [ ]+, [ ]{2,}, and \s+ suitable for replacing variable-length sequences.

Which Java regex should you use for extra spaces?

RequirementJava expression
Collapse one or more ordinary spacestext.replaceAll("[ ]+", " ")
Replace only runs of two or more ordinary spacestext.replaceAll("[ ]{2,}", " ")
Collapse regex whitespace such as spaces and tabstext.replaceAll("\\s+", " ")
Collapse ordinary spaces and remove surrounding whitespacetext.replaceAll("[ ]+", " ").trim()

Java multiple-space replacement summary

In this Java Tutorial, we learned how to replace adjacent spaces with a single space using String.replaceAll(). Use [ ]+ for ordinary spaces, [ ]{2,} when only repeated spaces should match, and \s+ when the input may contain other regex whitespace characters such as tabs. When leading or trailing whitespace must also be removed, normalize the text and then use trim() or, where appropriate, strip().