首页 > 解决方案 > Remove every space EXCEPT leading spaces

问题描述

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 ?

标签: javastringtrim

解决方案


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"

推荐阅读