1 package org.apache.lucene.search; 2 3 18 19 import java.io.IOException ; 20 21 import org.apache.lucene.index.IndexReader; 22 import org.apache.lucene.index.Term; 23 24 33 public class WildcardTermEnum extends FilteredTermEnum { 34 Term searchTerm; 35 String field = ""; 36 String text = ""; 37 String pre = ""; 38 int preLen = 0; 39 boolean endEnum = false; 40 41 49 public WildcardTermEnum(IndexReader reader, Term term) throws IOException { 50 super(); 51 searchTerm = term; 52 field = searchTerm.field(); 53 text = searchTerm.text(); 54 55 int sidx = text.indexOf(WILDCARD_STRING); 56 int cidx = text.indexOf(WILDCARD_CHAR); 57 int idx = sidx; 58 if (idx == -1) { 59 idx = cidx; 60 } 61 else if (cidx >= 0) { 62 idx = Math.min(idx, cidx); 63 } 64 65 pre = searchTerm.text().substring(0,idx); 66 preLen = pre.length(); 67 text = text.substring(preLen); 68 setEnum(reader.terms(new Term(searchTerm.field(), pre))); 69 } 70 71 protected final boolean termCompare(Term term) { 72 if (field == term.field()) { 73 String searchText = term.text(); 74 if (searchText.startsWith(pre)) { 75 return wildcardEquals(text, 0, searchText, preLen); 76 } 77 } 78 endEnum = true; 79 return false; 80 } 81 82 public final float difference() { 83 return 1.0f; 84 } 85 86 public final boolean endEnum() { 87 return endEnum; 88 } 89 90 93 94 public static final char WILDCARD_STRING = '*'; 95 public static final char WILDCARD_CHAR = '?'; 96 97 102 public static final boolean wildcardEquals(String pattern, int patternIdx, 103 String string, int stringIdx) 104 { 105 int p = patternIdx; 106 107 for (int s = stringIdx; ; ++p, ++s) 108 { 109 boolean sEnd = (s >= string.length()); 111 boolean pEnd = (p >= pattern.length()); 113 114 if (sEnd) 116 { 117 boolean justWildcardsLeft = true; 119 120 int wildcardSearchPos = p; 122 while (wildcardSearchPos < pattern.length() && justWildcardsLeft) 125 { 126 char wildchar = pattern.charAt(wildcardSearchPos); 128 129 if (wildchar != WILDCARD_CHAR && wildchar != WILDCARD_STRING) 132 { 133 justWildcardsLeft = false; 134 } 135 else 136 { 137 if (wildchar == WILDCARD_CHAR) { 139 return false; 140 } 141 142 wildcardSearchPos++; 144 } 145 } 146 147 if (justWildcardsLeft) 150 { 151 return true; 152 } 153 } 154 155 if (sEnd || pEnd) 158 { 159 break; 160 } 161 162 if (pattern.charAt(p) == WILDCARD_CHAR) 164 { 165 continue; 166 } 167 168 if (pattern.charAt(p) == WILDCARD_STRING) 170 { 171 ++p; 173 for (int i = string.length(); i >= s; --i) 175 { 176 if (wildcardEquals(pattern, p, string, i)) 177 { 178 return true; 179 } 180 } 181 break; 182 } 183 if (pattern.charAt(p) != string.charAt(s)) 184 { 185 break; 186 } 187 } 188 return false; 189 } 190 191 public void close() throws IOException 192 { 193 super.close(); 194 searchTerm = null; 195 field = null; 196 text = null; 197 } 198 } 199 | Popular Tags |