java 解析正则表达式多个捕获组

java parse regex multiple capture groups

嗨,我需要能够处理这两种情况

John, party of 4
william, party of 6 dislikes John, jeff

我要捕捉的是

我对如何实现这个感到很困惑

我知道 ([^,])+ 给了我第一组(只是逗号前的名字,不包括逗号)但我不知道如何连接表达式的其他部分。

您可以使用

(\w+)(?:,\s*party of (\d+)|(?![^,]))

参见regex demo

详情

  • (\w+) - 第 1 组:一个或多个单词字符
  • (?:,\s*party of (\d+)|(?![^,])) - 非捕获组匹配
    • ,\s*party of (\d+) - ,,然后是 0+ 白spaces,然后是 party of 和一个 space,然后第 2 组捕获 1+ 个数字
    • | - 或
    • (?![^,]) - 后跟 , 或字符串结尾的位置。

See Java demo:

String regex = "(\w+)(?:,\s*party of (\d+)|(?![^,]))";
List<String> strings = Arrays.asList("John, party of 4", "william, party of 6 dislikes John, jeff");

Pattern pattern = Pattern.compile(regex);
for (String s : strings) {
    System.out.println("-------- Testing '" + s + "':");
    Matcher matcher = pattern.matcher(s);
    while (matcher.find()) {
        System.out.println(matcher.group(1) + ": " + (matcher.group(2) != null ? matcher.group(2) : "N/A"));
    }
}

输出:

-------- Testing 'John, party of 4':
John: 4
-------- Testing 'william, party of 6 dislikes John, jeff':
william: 6
John: N/A
jeff: N/A