侧边栏壁纸
博主头像
落叶人生博主等级

走进秋风,寻找秋天的落叶

  • 累计撰写 130562 篇文章
  • 累计创建 28 个标签
  • 累计收到 9 条评论
标签搜索

目 录CONTENT

文章目录

检查字符串是否包含多个关键字的高级进阶

2022-11-26 星期六 / 0 评论 / 0 点赞 / 45 阅读 / 8383 字

简介在本快速教程中,将了解如何检测字符串中的多个单词。我们的例子我们假设我们有字符串:String inputString = "hello there, william";我们的任务是查找input

简介

在本快速教程中,将了解如何检测字符串中的多个单词。

我们的例子

我们假设我们有字符串:

String inputString = "hello there, william";

我们的任务是查找inputString 是否包含“hello”和“william”字样。

所以,让我们把我们的关键字放到一个数组中:

String[] words = {"hello", "william"};

此外,单词的顺序并不重要,匹配要区分大小写。

使用String.contains()

首先,我们将展示如何使用String.contains()方法来实现我们的目标

让我们遍历关键字数组并检查inputString中每个项目的出现 :

public static boolean containsWords(String inputString, String[] items) {    boolean found = true;    for (String item : items) {        if (!inputString.contains(item)) {            found = false;            break;        }    }    return found;}

这个例子比较简单易懂,尽管我们需要编写更多代码,但这种解决方案对于简单的用例来说速度很快。

使用 String.indexOf()

与使用String.contains()方法的解决方案类似,我们可以使用String.indexOf()方法检查关键字的索引。为此,我们需要一个接受inputString和关键字列表的方法:

public static boolean containsWordsIndexOf(String inputString, String[] words) {    boolean found = true;    for (String word : words) {        if (inputString.indexOf(word) == -1) {            found = false;            break;        }    }    return found;}

所述的indexOf() 方法返回的内部的字的索引inputString。当我们在文本中没有单词时,索引将为-1。

使用正则表达式

现在,让我们使用正则表达式来匹配我们的单词。为此,我们将使用Pattern类。

首先,让我们定义字符串表达式。由于我们需要匹配两个关键字,我们将使用两个前瞻构建我们的正则表达式规则:

Pattern pattern = Pattern.compile("(?=.*hello)(?=.*william)");

对于一般情况:

StringBuilder regexp = new StringBuilder();for (String word : words) {    regexp.append("(?=.*").append(word).append(")");}

之后,我们将使用matcher()方法find()出现次数:

public static boolean containsWordsPatternMatch(String inputString, String[] words) {     StringBuilder regexp = new StringBuilder();    for (String word : words) {        regexp.append("(?=.*").append(word).append(")");    }     Pattern pattern = Pattern.compile(regexp.toString());     return pattern.matcher(inputString).find();}

但是,正则表达式具有性能成本。如果我们要查找多个单词,则此解决方案的性能可能不是最佳的。

使用Java 8和List

最后,我们可以使用Java 8的Stream API。但首先,得把初始数据进行一些简单的转换:

List<String> inputString = Arrays.asList(inputString.split(" "));List<String> words = Arrays.asList(words);

现在,是时候使用Stream API了:

public static boolean containsWordsJava8(String inputString, String[] words) {    List<String> inputStringList = Arrays.asList(inputString.split(" "));    List<String> wordsList = Arrays.asList(words);     return wordsList.stream().allMatch(inputStringList::contains);}

如果输入字符串包含我们所有的关键字,则上面的操作将返回true

或者,我们可以简单地使用Collections框架的containsAll()方法来实现所需的结果:

public static boolean containsWordsArray(String inputString, String[] words) {    List<String> inputStringList = Arrays.asList(inputString.split(" "));    List<String> wordsList = Arrays.asList(words);     return inputStringList.containsAll(wordsList);}

但是,此方法仅适用于整个单词。因此,只有当它们与文本中的空格分开时才会找到我们的关键字。

使用Aho-Corasick算法

简而言之,Aho-Corasick算法用于使用多个关键字进行文本搜索。无论我们搜索多少关键字或文本长度是多长,它都具有O(n)时间复杂度

让我们在pom.xml中包含  Aho-Corasick算法依赖

<dependency>    <groupId>org.ahocorasick</groupId>    <artifactId>ahocorasick</artifactId>    <version>0.4.0</version></dependency>

首先,通过maven引入依赖包,内部的结构,将使用树形数据结构:

Trie trie = Trie.builder().onlyWholeWords().addKeywords(words).build();

之后,让我们使用inputString文本调用解析器方法,我们希望在其中找到关键字并将结果保存在emits集合中:

Collection<Emit> emits = trie.parseText(inputString);

最后,打印运行的结果:

emits.forEach(System.out::println);

对于每个关键字,我们会在文本中查看关键字的起始位置,结束位置和关键字本身:

0:4=hello13:19=william

最后,让我们看看完整的实现:

public static boolean containsWordsAhoCorasick(String inputString, String[] words) {    Trie trie = Trie.builder().onlyWholeWords().addKeywords(words).build();     Collection<Emit> emits = trie.parseText(inputString);    emits.forEach(System.out::println);     boolean found = true;    for(String word : words) {        boolean contains = Arrays.toString(emits.toArray()).contains(word);        if (!contains) {            found = false;            break;        }    }     return found;}

在这个例子中,我们只寻找整个单词。因此,如果我们不仅要匹配inputString而且还要匹配 helloBaeldung,我们应该简单地从Trie构建器管道中删除 onlyWholeWords()属性。

此外,请记住,我们还会从emits集合中删除重复元素,因为同一关键字可能存在多个匹配项。

结论

在本文中,我们学习了如何在字符串中查找多个关键字。此外,我们通过使用核心JDK以及Aho-Corasick库来展示示例

.
.

广告 广告

评论区