2
我使用的是lucene.Net版本3.0.3。我想做正則表達式搜索。我嘗試下面的代碼:如何使用lucene.Net進行正則表達式搜索
// 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版進行正則表達式搜索?
感謝femToRgon。我嘗試了你提到的解決方案。我手動構建了RegexQuery,它工作正常。 –