Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am looking for a Java regex way of replacing multiple spaces with non-breaking spaces. Two or more whitespaces should be replaced with the same number of non-breaking spaces, but single whitespaces should NOT be replaced. This needs to work for any number of whitespaces. And the first characters could be 1 or more whitespaces.

So if my String starts off like this:

TESTING THIS  OUT   WITH    DIFFERENT     CASES

I need the new String to look like this:

TESTING THIS  OUT   WITH    DIFFERENT     CASES
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
552 views
Welcome To Ask or Share your Answers For Others

1 Answer

Let's use some regex (black ?) magic.

String testStr = "TESTING THIS  OUT   WITH    DIFFERENT     CASES";
Pattern p = Pattern.compile(" (?= )|(?<= ) ");
Matcher m = p.matcher(testStr);
String res = m.replaceAll("&nbsp;");

The pattern looks for either a whitespace followed by another one, or a whitespace following another one. This way it catches all blanks in a sequence. On my machine, with java 1.6, I get the expected result:

TESTING THIS&nbsp;&nbsp;OUT&nbsp;&nbsp;&nbsp;WITH&nbsp;&nbsp;&nbsp;&nbsp;DIFFERENT&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;CASES

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...