Java 查找匹配器找到匹配的捕获组

Java 查找匹配器找到匹配的捕获组,java,regex,matcher,Java,Regex,Matcher,我有一个带有多个捕获组的正则表达式: String regex = "(first|second|third)|(one|two|three)|(uno|dos|tres)"; 我可以遍历字符串从每个组中查找模式: String text = "one two uno third second tres"; Matcher matcher = Pattern.compile(regex).matcher(text); for(int index = 0; matcher.find(index)

我有一个带有多个捕获组的正则表达式:

String regex = "(first|second|third)|(one|two|three)|(uno|dos|tres)";
我可以遍历
字符串
从每个组中查找模式:

String text = "one two uno third second tres";
Matcher matcher = Pattern.compile(regex).matcher(text);
for(int index = 0; matcher.find(index); index = matcher.end()) {
    System.out.println(matcher.group());
}
问题是,它没有告诉我它来自哪个群体

我可以将找到的组与每个可用组的
matcher.group(#)
进行比较,然后选择不返回
null的组:

int numOfGroups = 3;
for(int index = 0; matcher.find(index); index = matcher.end()) {
    String result = null;
    int group = 0;

    for(int i = 1; i <= numOfGroups; i++) {
        String tmp = matcher.group(i);
        if(tmp != null) {
            result = tmp;
            group = i;
            break;
        }
    }
    System.out.println(result + " " + group);
}
int numOfGroups=3;
for(int index=0;matcher.find(index);index=matcher.end()){
字符串结果=null;
int组=0;

对于(int i=1;i一个
匹配器
数组,每个
模式一个怎么样?您不会识别哪个组触发了匹配,但是哪个
匹配器
具有匹配

public static void main(String[] args) throws Exception {
    String text = "one two uno third second tres";
    Matcher[] matcher = { 
        Pattern.compile("(first|second|third)").matcher(text),
        Pattern.compile("(one|two|three)").matcher(text),
        Pattern.compile("(uno|dos|tres)").matcher(text)
    };

    for (int i = 0; i < matcher.length; i++) {
        while (matcher[i].find()) {
            System.out.println(matcher[i].group() + " " + i);
        }
    }
}

那么一个
匹配器
数组如何,每个
模式一个呢?您不会识别哪个组触发了匹配,而是哪个
匹配器
具有匹配

public static void main(String[] args) throws Exception {
    String text = "one two uno third second tres";
    Matcher[] matcher = { 
        Pattern.compile("(first|second|third)").matcher(text),
        Pattern.compile("(one|two|three)").matcher(text),
        Pattern.compile("(uno|dos|tres)").matcher(text)
    };

    for (int i = 0; i < matcher.length; i++) {
        while (matcher[i].find()) {
            System.out.println(matcher[i].group() + " " + i);
        }
    }
}

检查哪个组匹配,实际上不会增加任何性能开销。没有什么灵丹妙药可以让您获得信息。例如,引擎不够聪明,无法知道您只想匹配一个组。重要的是(对您而言)将其用作标志。通过只检查前两个组(如果它们都为
null
s),可以将复杂性降低一。最后一个组必须是具有匹配的组。另一个想法可能是为每种语言使用单独的模式。这样,您将知道正在使用的模式。检查哪个组匹配,不会增加任何性能开销真的。没有什么灵丹妙药可以让你获得信息。例如,引擎不够聪明,不知道你只想匹配一组。重要的是(对你来说)将其用作标志。通过只检查前两个组(如果它们都
null
s),可以将复杂性降低一。最后一个组必须是匹配的组。另一个想法可能是为每种语言使用单独的模式。这样,您将知道您使用的是哪种模式。