1 package org.apache.lucene.queryParser.surround.query;
3 * Licensed to the Apache Software Foundation (ASF) under one or more
4 * contributor license agreements. See the NOTICE file distributed with
5 * this work for additional information regarding copyright ownership.
6 * The ASF licenses this file to You under the Apache License, Version 2.0
7 * (the "License"); you may not use this file except in compliance with
8 * the License. You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
19 import org.apache.lucene.index.Term;
20 import org.apache.lucene.index.TermEnum;
21 import org.apache.lucene.index.IndexReader;
23 import java.io.IOException;
25 import java.util.regex.Pattern;
26 import java.util.regex.Matcher;
29 public class SrndTruncQuery extends SimpleTerm {
30 public SrndTruncQuery(String truncated, char unlimited, char mask) {
31 super(false); /* not quoted */
32 this.truncated = truncated;
33 this.unlimited = unlimited;
35 truncatedToPrefixAndPattern();
38 private final String truncated;
39 private final char unlimited;
40 private final char mask;
42 private String prefix;
43 private Pattern pattern;
46 public String getTruncated() {return truncated;}
49 public String toStringUnquoted() {return getTruncated();}
52 protected boolean matchingChar(char c) {
53 return (c != unlimited) && (c != mask);
56 protected void appendRegExpForChar(char c, StringBuilder re) {
65 protected void truncatedToPrefixAndPattern() {
67 while ((i < truncated.length()) && matchingChar(truncated.charAt(i))) {
70 prefix = truncated.substring(0, i);
72 StringBuilder re = new StringBuilder();
73 while (i < truncated.length()) {
74 appendRegExpForChar(truncated.charAt(i), re);
77 pattern = Pattern.compile(re.toString());
81 public void visitMatchingTerms(
84 MatchingTermVisitor mtv) throws IOException
86 int prefixLength = prefix.length();
87 TermEnum enumerator = reader.terms(new Term(fieldName, prefix));
88 Matcher matcher = pattern.matcher("");
91 Term term = enumerator.term();
93 String text = term.text();
94 if ((! text.startsWith(prefix)) || (! term.field().equals(fieldName))) {
97 matcher.reset( text.substring(prefixLength));
98 if (matcher.matches()) {
99 mtv.visitMatchingTerm(term);
103 } while (enumerator.next());