Edit:. This does not process punctuation marks and processes it to process punctuation marks, so you need to use the same approach as Sergio's answer, but with two steps instead of one. Therefore, this is an inadequate response and has been recalled.
Original answer below:
The easiest way I can think of is a two-step method.
First replace all spaces with "& nbsp;". This is pretty fast because it doesn't have to be a regex.
String testStr = "TESTING THIS OUT WITH DIFFERENT CASES"; String replaced = testStr.replace(" ", " ");
Then replace all individual instances of "& nbsp;" with spaces.
String replaced2 = replaced.replaceAll("\\b \\b", " "); System.out.println(replaced2);
Result:
TESTING THIS OUT WITH DIFFERENT CASES
Michael myers
source share