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

后端 未结 3 2164
时光取名叫无心
时光取名叫无心 2020-12-11 06:12

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

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-11 06:45

    You could also skip the regex all together.

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

    I haven't tested this but the first one finds all cases of two spaces and replaces them with non-breaking spaces. The second finds cases where there were an odd number of white-spaces and corrects it with two nbsps.

提交回复
热议问题