如何使用lucene进行正则表达式搜索网
本文关键字:正则表达式 搜索网 何使用 lucene | 更新日期: 2023-09-27 18:23:40
我正在使用lucene。Net 3.0.3。我想做正则表达式搜索。我尝试了以下代码:
// code
String SearchExpression = "[DM]ouglas";
const int hitsLimit = 1000000;
//state the file location of the index
string indexFileLocation = IndexLocation;
Lucene.Net.Store.Directory dir = Lucene.Net.Store.FSDirectory.Open(indexFileLocation);
//create an index searcher that will perform the search
Lucene.Net.Search.IndexSearcher searcher = new Lucene.Net.Search.IndexSearcher(dir);
var analyzer = new WhitespaceAnalyzer();
var parser = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_30, new[] {
Field_Content, }, analyzer);
Term t = new Term(Field_Content, SearchExpression);
RegexQuery scriptQuery = new RegexQuery(t);
string s = string.Format("{0}", SearchExpression);
var query = parser.Parse(s);
BooleanQuery booleanQuery = new BooleanQuery();
booleanQuery.Add(query, Occur.MUST);
var hits = searcher.Search(booleanQuery, null, hitsLimit, Sort.RELEVANCE).ScoreDocs;
foreach (var hit in hits)
{
var hitDocument = searcher.Doc(hit.Doc);
string contentValue = hitDocument.Get(Field_Content);
}
// end of code
当我尝试使用模式"Do*uglas"
进行搜索时,我会得到结果。
但如果我用模式"[DM]ouglas]"
搜索,它会给我以下错误:
"Cannot parse '[DM]ouglas': Encountered " "]" "] "" at line 1, column 3. Was expecting one of: "TO" ... <RANGEIN_QUOTED> ... <RANGEIN_GOOP> ...".
我还尝试了像".ouglas"
这样的简单搜索模式,它应该会给我结果,因为我的文本内容中有"Douglas"
。
有人知道如何使用lucene进行正则表达式搜索吗。Net版本3.0.3?
如果您希望使用正则表达式进行搜索,则需要手动构建RegexQuery
。请注意,RegexQuery
的性能往往较差。您可以通过从JavaUtilRegexCapabilities
切换到JakartaRegexpCapabilities
来改进它。