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

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

html - Java Regex that only replaces multiple whitepaces with Non-Breaking Spaces

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...