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
- Match and replace with
_+$
: any sequence of spaces at the end of the string- Match and replace with
$1
, which captures the empty string
- Match and replace with
(_)+
: 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
- Match and replace with