-1

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

简单的例子:

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

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

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

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

4

1 回答 1

1

构造正则表达式以使用命名组

(?<tag>wordA)|(?<wordx>wordX)|(?<anotherword>anotherword)
于 2016-12-13T00:31:13.057 回答