REGEX匹配任何/所有组

时间:2017-05-28 10:07:28

标签: java regex

while (matcher.find()) {
    if (matcher.group(matcherGroup) != null) occurrence++;
}
return occurrence;

这是我用来搜索特定群组匹配数量的代码。但是,没有像matcher.group(matcherGroup1, matcherGroup2)这样的功能,也没有matcher.group(null)来搜索多个组或所有组。

我已阅读Link组(将数组分组为一组)或多组?

由于

1 个答案:

答案 0 :(得分:0)

你能编写自己的matcherGroup实现吗?您提供的链接是c#。

我编写了一个简单的Java实现,它接受一个字符串,然后将它与多个RegExp模式匹配。然后返回匹配数。

或者,请更详细地解释您要做的事情。

package com.chocksaway;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

class SingleMatcher {
    private Pattern pattern;
    private java.util.regex.Matcher matcher;
    private boolean found;

    SingleMatcher(String input, String inputPattern) {
        pattern = Pattern.compile(inputPattern);
        matcher = pattern.matcher(input);

        if (matcher.find()) {
            this.found = true;
        }
    }

    boolean getFound() {
        return this.found;
    }
}

class MatcherGroup {
    private int matchedOccurances;

    MatcherGroup(String input, List<String> multipleInputPattern) {
        for (String inputPattern : multipleInputPattern) {
            SingleMatcher eachSingleMatcher = new SingleMatcher(input, inputPattern);
            if (eachSingleMatcher.getFound()) {
                matchedOccurances++;
            }
        }
    }

    int getMatchedOccurances() {
        return this.matchedOccurances;
    }
}

/**
* Author milesd on 28/05/2017.
*/
public class RegExpMatcher {
    public static void main(String[] args) {
        SingleMatcher singleMatcher = new SingleMatcher("123", "\\d\\d\\d");
        System.out.println(singleMatcher.getFound());

        List<String> inputPatternList = new ArrayList<String>();
        inputPatternList.add("\\d\\d\\d");
        inputPatternList.add("John");

        MatcherGroup matcherGroup = new MatcherGroup("John", inputPatternList);
        System.out.println(matcherGroup.getMatchedOccurances());

    }
}