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

后端 未结 3 2162
时光取名叫无心
时光取名叫无心 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:18

    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
    

提交回复
热议问题