0

Using Java, how can I replace all consecutive white spaces with a single space, in an elegant and simple way?

I am aware of str.replaceAll("\\s+", " "); but this replaces \n and other things too. I only want to replace multiple one after another with a single .

CubeJockey
  • 2,201
  • 8
  • 23
  • 31
We're All Mad Here
  • 1,534
  • 3
  • 17
  • 43

1 Answers1

2

Most regex flavors considers \n as whitespace. Same about \r or \t.

If you want to replace only one or more " " the simply use replaceAll(" +", " ")

Pshemo
  • 118,400
  • 24
  • 176
  • 257
  • `yourAnswer.replaceAll("Most","All")` ??? :) I've never heard of one that didn't. – ajb Dec 31 '15 at 17:48