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 spa
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(" ");
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 OUT WITH DIFFERENT CASES