在下面的句子中:

String res = [what, ask, about, group, differences, , , or, differences, in, conditions, |? |]

我要删除单个逗号(,),但不想删除三个相邻的逗号。

我尝试使用此正则表达式:res.replaceAll("(,\\s)^[(,\\s){3}]", " "),但无法正常工作。

最佳答案

一种简单的方法是链接两个replaceAll调用,而不是仅使用一种模式:

String input =
"[what, ask, about, group, differences, , , or, differences, in, conditions, |? |]";

System.out.println(
    input
        // replaces
        //           | comma+space not preceded/followed by other comma
        //           |                 | with space
        .replaceAll("(?<!, ), (?!,)", " ")
        // replaces
        //           | 3 consecutive comma+spaces
        //           |          | with single comma+space
        .replaceAll("(, ){3}", ", ")
);

输出
[what ask about group differences, or differences in conditions |? |]

09-26 15:37