pylucene 3.5.0-3
[pylucene.git] / lucene-java-3.5.0 / lucene / contrib / queries / src / java / org / apache / lucene / search / regex / RegexTermEnum.java
1 package org.apache.lucene.search.regex;
2
3 /**
4  * Licensed to the Apache Software Foundation (ASF) under one or more
5  * contributor license agreements.  See the NOTICE file distributed with
6  * this work for additional information regarding copyright ownership.
7  * The ASF licenses this file to You under the Apache License, Version 2.0
8  * (the "License"); you may not use this file except in compliance with
9  * the License.  You may obtain a copy of the License at
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19
20 import org.apache.lucene.search.FilteredTermEnum;
21 import org.apache.lucene.index.IndexReader;
22 import org.apache.lucene.index.Term;
23
24 import java.io.IOException;
25
26 /**
27  * Subclass of FilteredTermEnum for enumerating all terms that match the
28  * specified regular expression term using the specified regular expression
29  * implementation.
30  * <p>
31  * Term enumerations are always ordered by Term.compareTo().  Each term in
32  * the enumeration is greater than all that precede it.
33  */
34
35 public class RegexTermEnum extends FilteredTermEnum {
36   private String field = "";
37   private String pre = "";
38   private boolean endEnum = false;
39   private RegexCapabilities regexImpl;
40
41   public RegexTermEnum(IndexReader reader, Term term, RegexCapabilities regexImpl) throws IOException {
42     super();
43     field = term.field();
44     String text = term.text();
45     this.regexImpl = regexImpl;
46
47     regexImpl.compile(text);
48
49     pre = regexImpl.prefix();
50     if (pre == null) pre = "";
51
52     setEnum(reader.terms(new Term(term.field(), pre)));
53   }
54
55   @Override
56   protected final boolean termCompare(Term term) {
57     if (field == term.field()) {
58       String searchText = term.text();
59       if (searchText.startsWith(pre)) {
60         return regexImpl.match(searchText);
61       }
62     }
63     endEnum = true;
64     return false;
65   }
66
67   @Override
68   public final float difference() {
69 // TODO: adjust difference based on distance of searchTerm.text() and term().text()
70     return 1.0f;
71   }
72
73   @Override
74   public final boolean endEnum() {
75     return endEnum;
76   }
77
78   @Override
79   public void close() throws IOException {
80     super.close();
81     field = null;
82   }
83 }