【发布时间】:2018-07-17 01:21:55
【问题描述】:
我正在搜索段落中的单词,但长段落需要很长时间。因此,我想在段落中找到单词后将其删除,以减少必须经过的单词数。或者如果有更好的方法来提高效率,请告诉!
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 是"I ate an apple, but I am still hungry, so I will eat pie"
我想在paragraph 中找到wordList 中的单词并消除它们以希望使上面的代码更快
【问题讨论】:
-
I want to remove the words...您指的是哪个单词?您能否通过示例数据向我们展示您的意思? -
@TimBiegeleisen 我进行了编辑以提供示例,对不起!
-
只需将正则表达式更改为
String regex = "\\b" + Pattern.quote(word) + "\\b";,您的代码速度就会更快。虽然你有Pattern.quote,但它一定是String regex = "(?<!\\w)" + Pattern.quote(word) + "(?!\\w)"; -
好的,我得到了你需要的东西。尝试this code on your side,通过
@Wiktor的评论让我知道,如果可行,我将发布解释。如果单词列表中只有字母、数字或_s 组成的单词,则可以使用lighter version。 -
见ideone.com/xVFuGP。请参阅下面的答案。
标签: java regex string parsing matcher