java - 如何将文本文件与多个正则表达式模式进行匹配并计算这些模式的出现次数?

标签 java regex count matcher find-occurrences

我想分别在文本文件的每一行中查找并统计单词单元、设备、方法、模块的所有出现次数。这就是我所做的,但我不知道如何使用多个模式以及如何分别计算行中每个单词的出现次数?现在它只计算每一行所有单词的出现次数。提前致谢!

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

最佳答案

最好使用单词边界并使用 map 来记录每个匹配关键字的数量。

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

关于java - 如何将文本文件与多个正则表达式模式进行匹配并计算这些模式的出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33423994/

相关文章:

java - 如何在 javac/java 类路径中添加多个 .jar 文件 - 适用于 Debian Linux

java - JVM 前 4 个 boolean 值优化,而不是第 5 个

java - 野蝇作为系统服务

c++ - 防撞正则表达式?

python - 计算 python 中连续 1 的个数

php - 两个计数之间的差异

java - WebLogic javax.net.ssl.SSLHandshakeException

Javascript 正则表达式匹配数组无法正常工作

mysql - 更好的做法 : saving count result into field or not?

regex - 如何使用正则表达式执行proxypassreverse