gpt4 book ai didi

java - 使用 Lucene 的 RegexQuery 时匹配的片段

转载 作者:行者123 更新时间:2023-12-01 15:55:26 25 4
gpt4 key购买 nike

我正在使用 RegexQuery 对 Lucene 索引执行查询操作。例如,我使用 new RegexQuery(new Term("text", "https?://[^\\s]+") 执行 RegexQuery 来获取包含 URL 的所有文档(I要知道,正则表达式过于简化了)。

现在我想检索实际上与我的查询匹配的文本片段,例如http://example.com。 Lucene 是否提供了一种有效的可能性?或者我是否使用 Java 的 RegEx 匹配器再次处理整个文本?

最佳答案

我认为你真正想要的东西是不可能的,但这里有一种不同的方法,具有类似的效果:

打开索引阅读器,获取“http”之后的所有术语(按字典顺序 1 排序),直到它们不再以“http://”或“https://”开头:

    final IndexReader reader = IndexReader.open(IndexHelper.DIRECTORY, true);
final TermEnum termEnum = reader.terms(new Term("text", "http"));
final List<Term> terms = new ArrayList<Term>();
Term foundTerm = termEnum.term();

// if the first term does not match url pattern: advance until it first matches
if (!(foundTerm.text().startsWith("https://") || foundTerm.text().startsWith("http://"))) {
while (termEnum.next()) {
foundTerm = termEnum.term();
if (foundTerm.text().startsWith("https://") || foundTerm.text().startsWith("http://")) {
break;
}
}
}
// collect all terms
while ((foundTerm.text().startsWith("https://") || foundTerm.text().startsWith("http://")) && termEnum.next()) {
foundTerm = termEnum.term();
terms.add(foundTerm);
}

生成的 URL 将出现在“terms”列表中,作为 lucene 术语。

这当然有一个缺点,即您无法获得找到这些 URL 的文档,但您可以随后使用找到的术语再次查询它们。

我在这里布置的方式不是很灵活(但可能更快地完成任务),但是您当然可以返回到模式以实现更大的灵 active 。然后你将替换所有 foundTerm.text().startsWith("https://") || foundTerm.text().startsWith("http://")yourPattern.matches(foundTerm.text())

抱歉我写了这么多^^。

希望对您有所帮助。

关于java - 使用 Lucene 的 RegexQuery 时匹配的片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5161802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com