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

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

    Edit: This does not handle punctuation, and reworking it to handle punctuation would require it to use the same approach as Sergio's answer but with two steps instead of one. Therefore, this is an inadequate answer and has been withdrawn.


    Original answer below:

    The most straightforward way that I can think of is a two-step method.

    First, replace all spaces with " ". 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(" ", " ");
    

    Next, replace any single instances of " " with spaces.

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

    Result:

    TESTING THIS  OUT   WITH    DIFFERENT     CASES
    

提交回复
热议问题