使用正则表达式搜索文本中的多个单词(Java)

问题描述 投票:0回答:2

我有一种方法可以在文本中搜索单词,两者都是通过参数插入的。

public Integer findTheWord(String stringToCheck, String regexString) throws IOException {

        int count = 0;
        Pattern regexp = Pattern.compile("\\b" + regexString + "\\b");
        Matcher matcher = regexp.matcher(stringToCheck);

        while (matcher.find()) {
                count++;
                String matchString = matcher.group();
                System.out.println(matchString);
            }
        System.out.println(count);
        return count;
  }

如何插入多个单词并返回每个单词出现的次数?

java regex string search
2个回答
1
投票

因此,第一个也是最简单的选择是使用实际的

findTheWord()
方法并创建一个使用它的新方法:

public Map<String, Integer> findTheWords(String stringToCheck, List<String> words) {
    return words.stream().distinct()
            .collect(Collectors.toMap(Function.identity(), word -> findTheWord(stringToCheck, word)));
}

public Integer findTheWord(String stringToCheck, String regexString) {
    Pattern regexp = Pattern.compile("\\b" + regexString + "\\b");
    Matcher matcher = regexp.matcher(stringToCheck);

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

这样做的问题是,如果您使用大量单词来查找和大型文本,因为它会迭代每个单词的给定字符串。因此,另一种方法是为所有单词创建一个正则表达式,并在结果映射中增加下一个找到的单词:

public Map<String, Integer> findTheWords(String stringToCheck, List<String> words) {
    Pattern regexp = Pattern.compile(words.stream().distinct().map(word -> "\\b" + word + "\\b").collect(Collectors.joining("|")));
    // creates a pattern like this: "\ba\b|\bb\b|\bc\b|\bd\b|\be\b"
    Matcher matcher = regexp.matcher(stringToCheck);
    Map<String, Integer> result = new HashMap<>();
    while (matcher.find()) {
        String word = matcher.group();
        result.put(word, result.getOrDefault(word, 0) + 1);
    }
    return result;
}

此外,您可能会考虑对单词使用

Set
而不是
List
,因为值是唯一的,因此无需在流上调用
.distinct()


1
投票

HashMap 作为参数,输入字符串作为键,正则表达式作为值,循环遍历所有条目,执行您的方法并返回一个 HashMap,其中匹配的单词作为键,出现次数作为值。

 public HashMap<String, Integer> findTheWordsAndOccurences(HashMap<String, String> stringsAndRegex) throws IOException {

    HashMap<String, Integer> result = null;

    for (Map.Entry<String, String> entry : stringsAndRegex.entrySet()){

        String stringToCheck = entry.getKey();
        String regexString = entry.getValue();
        String matchString = "";
        int count = 0;
        Pattern regexp = Pattern.compile("\\b" + regexString + "\\b");
        Matcher matcher = regexp.matcher(stringToCheck);

        while (matcher.find()) {
            count++;
            matchString = matcher.group();
            System.out.println(matchString);
            result.put(matchString, count);
        }
    }
    return result;
}
© www.soinside.com 2019 - 2024. All rights reserved.