我正在寻找段落中的单词,但对于长段落来说需要很长时间。因此,我想在段落中找到单词后将其删除,以缩短我必须浏览的单词数。或者如果有更好的方法来提高效率,请告诉我们!
List<String> list = new ArrayList<>();
for (String word : wordList) {
String regex = ".*\\b" + Pattern.quote(word) + "\\b.*";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(paragraph);
if (m.find()) {
System.out.println("Found: " + word);
list.add(word);
}
}
例如,假设我的 wordList
具有以下值 "apple","hungry","pie"
我的段落
是“我吃了一个苹果,但我还是饿,所以我会吃馅饼”
我想在paragraph
中找到wordList
中的单词并消除它们,希望使上面的代码更快
最佳答案
您可以使用
String paragraph = "I ate an apple, but I am still hungry, so I will eat pie";
List<String> wordList = Arrays.asList("apple","hungry","pie");
Pattern p = Pattern.compile("\\b(?:" + String.join("|", wordList) + ")\\b");
Matcher m = p.matcher(paragraph);
if (m.find()) { // To find all matches, replace "if" with "while"
System.out.println("Found " + m.group()); // => Found apple
}
请参阅Java demo .
正则表达式将类似于 \b(?:word1|word2|wordN)\b
并将匹配:
-
\b
- 单词边界 -
(?:word1|word2|wordN)
- 非捕获组内的任何替代方案 -
\b
- 单词边界
既然你说单词中的字符只能是大写字母、数字和带斜杠的连字符,所以都不需要转义,所以Pattern.quote
这里并不重要。此外,由于斜杠和连字符永远不会出现在字符串的开头/结尾,因此您不会遇到通常由 \b
引起的问题。词边界。否则,替换第一个 "\\b"
与 "(?<!\\w)"
最后一个是 "(?!\\w)"
.
关于java - 优化段落中查找单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51371952/