Java 删除单个逗号,但不使用';t删除句子中的3个相邻逗号

Java 删除单个逗号,但不使用';t删除句子中的3个相邻逗号,java,regex,Java,Regex,在下面的句子中: String res = [what, ask, about, group, differences, , , or, differences, in, conditions, |? |] 我想删除单个逗号(,),但不想删除三个相邻的逗号 我尝试使用这个正则表达式:res.replaceAll(“(,\\s)^[(,\\s){3}]”,“)但它不起作用。一个简单的方法是链接两个replaceAll调用,而不是只使用一个模式: String input = "[what, a

在下面的句子中:

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}", ", ")
);

您可以在
find
方法中使用此代码替换:

String s = "[what, ask, about, group, differences, , , or, differences, in, conditions, |? |]";
StringBuffer result = new StringBuffer();
Matcher m = Pattern.compile("((?:\\s*,){3})|,").matcher(s);
while (m.find()) {
    if (m.group(1) != null) {
        m.appendReplacement(result, ",");
    }
    else {
        m.appendReplacement(result, "");
    }
}
m.appendTail(result);
System.out.println(result.toString());

输出:
[关于组差异或条件差异的问题|?|]

regex-
((?:\\s*,){3})|,
-匹配两个可选项:3个逗号,用可选空格分隔(捕获),或仅一个逗号。如果我们得到一个捕获,我们将用逗号替换。如果捕获为空,则匹配单个逗号,将其删除。

您还可以使用:

String res = "[what, ask, about, group, differences, , , or, differences, in, conditions, |? |]";
res.replaceAll("(?<=\\w),(?!\\s,)|(?<!\\w),\\s","");
String res=“[what,ask,about,group,differences,,or,differences,in,conditions,|?|]”;

res.replaceAll((?另一种可能的方法:

.replaceAll("(,\\s){2,}|,", "$1")
  • (,\\s){2,}
    将尝试查找两个或多个
    ,并将其中一个存储在组中,索引为
    1
  • 可以匹配以前的正则表达式未使用的逗号,这意味着它是单个逗号
替换
$1
使用组1中的匹配项

  • 如果我们发现
    ,我们想用
    替换它,这样的文本将放在组1中
  • 如果我们只找到
    ,那么我们希望将其替换为零,因为早期的正则表达式无法找到匹配项,所以它的所有组(在我们的例子中是组1)也都是空的

您能发布您期望的结果吗?
.replaceAll("(,\\s){2,}|,", "$1")