'How to match the text file against multiple regex patterns and count the number of occurences of these patterns?

I want to find and count all the occurrences of the words unit, device, method, module in every line of the text file separately. That's what I've done, but I don't know how to use multiple patterns and how to count the occurrence of every word in the line separately? Now it counts only occurrences of all words together for every line. Thank you in advance!

private void countPaterns() throws IOException {

    Pattern nom = Pattern.compile("unit|device|method|module|material|process|system");

    String str = null;      

    BufferedReader r = new BufferedReader(new FileReader("D:/test/test1.txt")); 

    while ((str = r.readLine()) != null) {
        Matcher matcher = nom.matcher(str);

        int countnomen = 0;
        while (matcher.find()) {
            countnomen++;
        }

        //intList.add(countnomen);
        System.out.println(countnomen + " davon ist das Wort System");
    }
    r.close();
    //return intList;
}


Solution 1:[1]

Here's a Java 9 (and above) solution:

public static void main(String[] args) {
    List<String> expressions = List.of("(good)", "(bad)");
    String phrase = " good  bad     bad good   good bad bad bad";

    for (String regex : expressions) {
        Pattern gPattern = Pattern.compile(regex);
        Matcher matcher = gPattern.matcher(phrase);
        long count = matcher.results().count();
        System.out.println("Pattern \"" + regex + "\" appears " + count + (count == 1 ? " time" : " times"));
    }
}

Outputs

Pattern "(good)" appears 3 times
Pattern "(bad)" appears 5 times

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hfontanez