Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces java java

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces


Try this:

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

See also


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


You just need a:

replaceAll("\\s{2,}", " ").trim();

where you match one or more spaces and replace them with a single space and then trim whitespaces at the beginning and end (you could actually invert by first trimming and then matching to make the regex quicker as someone pointed out).

To test this out quickly try:

System.out.println(new String(" hello     there   ").trim().replaceAll("\\s{2,}", " "));

and it will return:

"hello there"


Use the Apache commons StringUtils.normalizeSpace(String str) method. See docs here