Remove every space EXCEPT leading spaces

Tags: , ,



I need to remove every spaces from a String EXCEPT leading spaces.

I have some strings that look like this :

"              h        ello"

And I am trying to achieve this :

"              hello"

That’s like a reverse trim().

What’s the most efficient way to go about it ?

Answer

You can use replaceAll with this regex (?<=S)(s+)(?=S) like this :

str = str.replaceAll("(?<=\S)(\s+)(?=\S)", "");

Examples of input & outputs:

"              h   ello  "        => "              hello  "
"              hello,  word  "    => "              hello,word  "

The first regex keep only leading and trailing spaces, if you want to keep only the leading spaces, then you can use this regex (?<=S)(s+).

Examples of input & outputs:

"              hello  "         => "              hello"
"              hello,  word  "  => "              hello,word"


Source: stackoverflow