Java Regex that replaces only a few white spaces with non-destructive spaces

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

So, if my line starts as follows:

TESTING THIS OUT WITH DIFFERENT CASES 

I need a new line to look like this:

 TESTING THIS  OUT   WITH    DIFFERENT     CASES 
+6
java html regex
source share
3 answers

You can also skip regex together.

 String testStr = "TESTING THIS OUT WITH DIFFERENT CASES"; String _replaced = testStr.replace(" ", "  "); String replaced = _replaced.replace("  ", "  "); 

I did not test this, but the first one found all cases of two spaces and replaced them with inextricable spaces. The second finds cases where there was an odd number of white spaces and fixed with two nbsps.

+2
source share

You can use the magic of regular expressions (black?).

 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 space followed by another, or a space following another. Thus, it captures all the gaps in the 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 
+4
source share

Edit:. This does not process punctuation marks and processes it to process punctuation marks, so you need to use the same approach as Sergio's answer, but with two steps instead of one. Therefore, this is an inadequate response and has been recalled.


Original answer below:

The easiest way I can think of is a two-step method.

First replace all spaces with "& nbsp;". This is pretty fast because it doesn't have to be a regex.

 String testStr = "TESTING THIS OUT WITH DIFFERENT CASES"; String replaced = testStr.replace(" ", "&nbsp;"); 

Then replace all individual instances of "& nbsp;" with spaces.

 String replaced2 = replaced.replaceAll("\\b&nbsp;\\b", " "); System.out.println(replaced2); 

Result:

 TESTING THIS&nbsp;&nbsp;OUT&nbsp;&nbsp;&nbsp;WITH&nbsp;&nbsp;&nbsp;&nbsp;DIFFERENT&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;CASES 
+2
source share

All Articles