Java 正则表达式 - 确定匹配的捕获组并计算出现次数

Java regex - Determine which capture group was matched and count occurences

假设我想根据用户的决定在 运行 时间构建一个带有捕获组的非常大的正则表达式。

简单示例:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {    
    static boolean findTag, findWordA, findOtherWord, findWordX;

    static final String TAG = "(<[^>]+>)";
    static final String WORD_A = "(wordA)";
    static final String OTHER_WORD = "(anotherword)";
    static final String WORD_X = "(wordX)";

    static int tagCount = 0;
    static int wordACount = 0;
    static int otherWordCount = 0;
    static int wordXCount = 0;

    public static void main(String[] args) {
        // Boolean options that will be supplied by the user
        // make them all true in this example
        findTag = true;
        findWordA = true;
        findOtherWord = true;
        findWordX = true;

        String input = "<b>this is an <i>input</i> string that contains wordX, wordX, anotherword and wordA</b>";

        StringBuilder regex = new StringBuilder();

        if (findTag)
            regex.append(TAG + "|");

        if (findWordA)
            regex.append(WORD_A + "|");

        if (findOtherWord)
            regex.append(OTHER_WORD + "|");

        if (findWordX)
            regex.append(WORD_X + "|");

        if (regex.length() > 0) {
            regex.setLength(regex.length() - 1);
            Pattern pattern = Pattern.compile(regex.toString());

            System.out.println("\nWHOLE REGEX: " + regex.toString());
            System.out.println("\nINPUT STRING: " + input);

            Matcher matcher = pattern.matcher(input);

            while (matcher.find()) {
                // only way I know of to find out which group was matched:
                if (matcher.group(1) != null) tagCount++;
                if (matcher.group(2) != null) wordACount++;
                if (matcher.group(3) != null) otherWordCount++;
                if (matcher.group(4) != null) wordXCount++;
            }

            System.out.println();
            System.out.println("Group1 matches: " + tagCount);
            System.out.println("Group2 matches: " + wordACount);
            System.out.println("Group3 matches: " + otherWordCount);
            System.out.println("Group4 matches: " + wordXCount);

        } else {
            System.out.println("No regex to build.");
        }
    }
}

问题是,只有当我事先知道用户想要查找哪个 regex/groups 时,我才能计算每个组的匹配项。

请注意,完整的正则表达式将包含更多的捕获组,并且它们会更加复杂。

如何确定哪个捕获组匹配,以便我可以计算每个组的出现次数,而无需事先知道用户想要查找哪些组?

构造要使用的正则表达式 named groups:

(?<tag>wordA)|(?<wordx>wordX)|(?<anotherword>anotherword)