获取在regex中进行匹配的组的编号/ ID

时间:2016-11-08 03:21:33

标签: java regex

我只编写了2个小时的代码,认为Matcher.group()返回了在regex中进行匹配的组的编号/ id。我所做的简化示例:

//    Group   -1-   -2- 
Pattern p = Pattern.compile("(abc)|(def)");
String t = "abc abc def def abc";

for (Matcher m = p.matcher(t); m.find(); ) {
    System.out.print( m.group() );
}

我认为这会输出1, 1, 2, 2, 1,即每场比赛的组数。相反,它实际上返回组匹配的部分。有没有其他方法或任何方法来达到我想要的结果?

1 个答案:

答案 0 :(得分:2)

您可以查看group结果以查看匹配的结果:

for (Matcher m = p.matcher(t); m.find(); ) {
    if (m.group(1) != null) {
        System.out.print("1, ");
    } else {
        System.out.print("2, ");
    }
}

编辑:如果你有很多小组并且不想对它们进行硬编码,你可以改为循环它们(假设它们仍然是独占的):

for (Matcher m = p.matcher(t); m.find(); ) {
    for (int i = 1; i <= m.groupCount(); i++) {
        if (m.group(i) != null) {
            System.out.print(i + ", ");
            break;
        }
    }
}