Java 如何根据多个正则表达式模式匹配文本文件并计算这些模式的出现次数?

Java 如何根据多个正则表达式模式匹配文本文件并计算这些模式的出现次数?,java,regex,count,matcher,find-occurrences,Java,Regex,Count,Matcher,Find Occurrences,我想分别在文本文件的每一行中查找并统计单词unit、device、method、module的出现次数。这就是我所做的,但我不知道如何使用多种模式,以及如何分别计算行中每个单词的出现次数?现在它只计算每行所有单词的出现次数。提前谢谢你 private void countPaterns() throws IOException { Pattern nom = Pattern.compile("unit|device|method|module|material|process|syst

我想分别在文本文件的每一行中查找并统计单词unit、device、method、module的出现次数。这就是我所做的,但我不知道如何使用多种模式,以及如何分别计算行中每个单词的出现次数?现在它只计算每行所有单词的出现次数。提前谢谢你

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;
}

最好使用单词边界并使用映射来保持每个匹配关键字的计数

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

String str = null;
BufferedReader r = new BufferedReader(new FileReader("D:/test/test1.txt"));
Map<String, Integer> counts = new HashMap<>();

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

    while (matcher.find()) {
        String key = matcher.group(1);
        int c = 0;
        if (counts.containsKey(key))
            c = counts.get(key);
        counts.put(key, c+1)
    }
}
r.close();

System.out.println(counts);
Pattern nom=Pattern.compile(\\b(单元|设备|方法|模块|材料|过程|系统)\\b);
字符串str=null;
BufferedReader r=新的BufferedReader(新文件读取器(“D:/test/test1.txt”);
映射计数=新的HashMap();
而((str=r.readLine())!=null){
匹配器匹配器=名称匹配器(str);
while(matcher.find()){
字符串键=matcher.group(1);
int c=0;
if(计数容器(键))
c=计数。获取(键);
计数。放置(键,c+1)
}
}
r、 close();
系统输出打印项次(计数);

请添加有用的标记,例如您使用的语言。“计数”、“匹配器”和“查找事件”对于此问题没有用处。谢谢!它的工作方式非常好,但唯一的问题是我得到了整个txt文件的出现次数。但我需要分别为每一行新的文本获取这个数字。在更改之前,它对每行都有效如果您希望每行计数,则在
Matcher Matcher=nom.Matcher(str)之后添加
counts.clear()
行,并确保在外部
循环中打印它。