0

I'm trying to replace all all spaces in string with one space. I'm trying this:

String src = "2.       Test Sentence with     spaces";
String out = src.replaceAll("\\s+", " ");
System.out.println(out);

And this is what I'm getting:

2.       Test Sentence with spaces

Spaces after dot were not replaced... Why?

Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
user2783755
  • 578
  • 2
  • 10
  • 26

1 Answers1

3

You can try with the Unicode category: separator, space, combined with whitespace:

String input = "\u0020\u00A0\u1680\u2000\u2001\t"; //etc. 17 characters
System.out.println(input.replaceAll("[\\p{Zs}\\s]+", " "));

Output

[1 space]

See here for the list of characters in category Zs.

Mena
  • 47,782
  • 11
  • 87
  • 106