Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

This question already has an answer here:

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?

share|improve this question

marked as duplicate by Joe, Pshemo java Sep 30 '14 at 15:08

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
it works for me.. – Avinash Raj Sep 30 '14 at 14:26
    
It works perfectly fine for me too. Is this your real code? – BackSlash Sep 30 '14 at 14:27
2  
Could you take a look at your program in your editor's hex mode - perhaps there are some strange Unicode codepoints where you think that there are just spaces? – Tim Pietzcker Sep 30 '14 at 14:28
    
So, in HEX mode there is "c2 a0 NO-BREAK SPACE" symbols... How can I replace ALL spaces? Thanks! – user2783755 Sep 30 '14 at 14:42
up vote 2 down vote accepted

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.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.