KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > pde > internal > ui > util > StringMatcher


1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.pde.internal.ui.util;
12
13 import java.util.Vector JavaDoc;
14
15 /**
16  * Copied from JDT UI
17  * A string pattern matcher. Supports '*' and '?' wildcards.
18  */

19 public class StringMatcher {
20     protected String JavaDoc fPattern;
21     protected int fLength; // pattern length
22
protected boolean fIgnoreWildCards;
23     protected boolean fIgnoreCase;
24     protected boolean fHasLeadingStar;
25     protected boolean fHasTrailingStar;
26     protected String JavaDoc fSegments[]; //the given pattern is split into * separated segments
27

28     /* boundary value beyond which we don't need to search in the text */
29     protected int fBound= 0;
30
31
32     protected static final char fSingleWildCard= '\u0000';
33
34     public static class Position {
35         int start; //inclusive
36
int end; //exclusive
37
public Position(int start, int end) {
38             this.start= start;
39             this.end= end;
40         }
41         public int getStart() {
42             return start;
43         }
44         public int getEnd() {
45             return end;
46         }
47     }
48     /**
49      * StringMatcher constructor takes in a String object that is a simple
50      * pattern. The pattern may contain '*' for 0 and many characters and
51      * '?' for exactly one character.
52      *
53      * Literal '*' and '?' characters must be escaped in the pattern
54      * e.g., "\*" means literal "*", etc.
55      *
56      * Escaping any other character (including the escape character itself),
57      * just results in that character in the pattern.
58      * e.g., "\a" means "a" and "\\" means "\"
59      *
60      * If invoking the StringMatcher with string literals in Java, don't forget
61      * escape characters are represented by "\\".
62      *
63      * @param pattern the pattern to match text against
64      * @param ignoreCase if true, case is ignored
65      * @param ignoreWildCards if true, wild cards and their escape sequences are ignored
66      * (everything is taken literally).
67      */

68     public StringMatcher(String JavaDoc pattern, boolean ignoreCase, boolean ignoreWildCards) {
69         if (pattern == null)
70             throw new IllegalArgumentException JavaDoc();
71         fIgnoreCase= ignoreCase;
72         fIgnoreWildCards= ignoreWildCards;
73         fPattern= pattern;
74         fLength= pattern.length();
75
76         if (fIgnoreWildCards) {
77             parseNoWildCards();
78         } else {
79             parseWildCards();
80         }
81     }
82     /**
83      * Find the first occurrence of the pattern between <code>start</code)(inclusive)
84      * and <code>end</code>(exclusive).
85      * @param text the String object to search in
86      * @param start the starting index of the search range, inclusive
87      * @param end the ending index of the search range, exclusive
88      * @return an <code>StringMatcher.Position</code> object that keeps the starting
89      * (inclusive) and ending positions (exclusive) of the first occurrence of the
90      * pattern in the specified range of the text; return null if not found or subtext
91      * is empty (start==end). A pair of zeros is returned if pattern is empty string
92      * Note that for pattern like "*abc*" with leading and trailing stars, position of "abc"
93      * is returned. For a pattern like"*??*" in text "abcdf", (1,3) is returned
94      */

95     public StringMatcher.Position find(String JavaDoc text, int start, int end) {
96         if (text == null)
97             throw new IllegalArgumentException JavaDoc();
98
99         int tlen= text.length();
100         if (start < 0)
101             start= 0;
102         if (end > tlen)
103             end= tlen;
104         if (end < 0 ||start >= end )
105             return null;
106         if (fLength == 0)
107             return new Position(start, start);
108         if (fIgnoreWildCards) {
109             int x= posIn(text, start, end);
110             if (x < 0)
111                 return null;
112             return new Position(x, x+fLength);
113         }
114
115         int segCount= fSegments.length;
116         if (segCount == 0)//pattern contains only '*'(s)
117
return new Position (start, end);
118
119         int curPos= start;
120         int matchStart= -1;
121         int i;
122         for (i= 0; i < segCount && curPos < end; ++i) {
123             String JavaDoc current= fSegments[i];
124             int nextMatch= regExpPosIn(text, curPos, end, current);
125             if (nextMatch < 0 )
126                 return null;
127             if(i == 0)
128                 matchStart= nextMatch;
129             curPos= nextMatch + current.length();
130         }
131         if (i < segCount)
132             return null;
133         return new Position(matchStart, curPos);
134     }
135     /**
136      * match the given <code>text</code> with the pattern
137      * @return true if matched eitherwise false
138      * @param text a String object
139      */

140     public boolean match(String JavaDoc text) {
141         return match(text, 0, text.length());
142     }
143     /**
144      * Given the starting (inclusive) and the ending (exclusive) positions in the
145      * <code>text</code>, determine if the given substring matches with aPattern
146      * @return true if the specified portion of the text matches the pattern
147      * @param text a String object that contains the substring to match
148      * @param start marks the starting position (inclusive) of the substring
149      * @param end marks the ending index (exclusive) of the substring
150      */

151     public boolean match(String JavaDoc text, int start, int end) {
152         if (null == text)
153             throw new IllegalArgumentException JavaDoc();
154
155         if (start > end)
156             return false;
157
158         if (fIgnoreWildCards)
159             return (end - start == fLength) && fPattern.regionMatches(fIgnoreCase, 0, text, start, fLength);
160         int segCount= fSegments.length;
161         if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) // pattern contains only '*'(s)
162
return true;
163         if (start == end)
164             return fLength == 0;
165         if (fLength == 0)
166             return start == end;
167
168         int tlen= text.length();
169         if (start < 0)
170             start= 0;
171         if (end > tlen)
172             end= tlen;
173
174         int tCurPos= start;
175         int bound= end - fBound;
176         if ( bound < 0)
177             return false;
178         int i=0;
179         String JavaDoc current= fSegments[i];
180         int segLength= current.length();
181
182         /* process first segment */
183         if (!fHasLeadingStar){
184             if(!regExpRegionMatches(text, start, current, 0, segLength)) {
185                 return false;
186             }
187             ++i;
188             tCurPos= tCurPos + segLength;
189         }
190         if ((fSegments.length == 1) && (!fHasLeadingStar) && (!fHasTrailingStar)) {
191             // only one segment to match, no wildcards specified
192
return tCurPos == end;
193         }
194         /* process middle segments */
195         while (i < segCount) {
196             current= fSegments[i];
197             int currentMatch;
198             int k= current.indexOf(fSingleWildCard);
199             if (k < 0) {
200                 currentMatch= textPosIn(text, tCurPos, end, current);
201                 if (currentMatch < 0)
202                     return false;
203             } else {
204                 currentMatch= regExpPosIn(text, tCurPos, end, current);
205                 if (currentMatch < 0)
206                     return false;
207             }
208             tCurPos= currentMatch + current.length();
209             i++;
210         }
211
212         /* process final segment */
213         if (!fHasTrailingStar && tCurPos != end) {
214             int clen= current.length();
215             return regExpRegionMatches(text, end - clen, current, 0, clen);
216         }
217         return i == segCount ;
218     }
219
220     /**
221      * This method parses the given pattern into segments seperated by wildcard '*' characters.
222      * Since wildcards are not being used in this case, the pattern consists of a single segment.
223      */

224     private void parseNoWildCards() {
225         fSegments= new String JavaDoc[1];
226         fSegments[0]= fPattern;
227         fBound= fLength;
228     }
229     /**
230      * Parses the given pattern into segments seperated by wildcard '*' characters.
231      */

232     private void parseWildCards() {
233         if(fPattern.startsWith("*"))//$NON-NLS-1$
234
fHasLeadingStar= true;
235         if(fPattern.endsWith("*")) {//$NON-NLS-1$
236
/* make sure it's not an escaped wildcard */
237             if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') {
238                 fHasTrailingStar= true;
239             }
240         }
241
242         Vector JavaDoc temp= new Vector JavaDoc();
243
244         int pos= 0;
245         StringBuffer JavaDoc buf= new StringBuffer JavaDoc();
246         while (pos < fLength) {
247             char c= fPattern.charAt(pos++);
248             switch (c) {
249             case '\\':
250                 if (pos >= fLength) {
251                     buf.append(c);
252                 } else {
253                     char next= fPattern.charAt(pos++);
254                     /* if it's an escape sequence */
255                     if (next == '*' || next == '?' || next == '\\') {
256                         buf.append(next);
257                     } else {
258                         /* not an escape sequence, just insert literally */
259                         buf.append(c);
260                         buf.append(next);
261                     }
262                 }
263                 break;
264             case '*':
265                 if (buf.length() > 0) {
266                     /* new segment */
267                     temp.addElement(buf.toString());
268                     fBound += buf.length();
269                     buf.setLength(0);
270                 }
271                 break;
272             case '?':
273                 /* append special character representing single match wildcard */
274                 buf.append(fSingleWildCard);
275                 break;
276             default:
277                 buf.append(c);
278             }
279         }
280
281         /* add last buffer to segment list */
282         if (buf.length() > 0) {
283             temp.addElement(buf.toString());
284             fBound += buf.length();
285         }
286
287         fSegments= new String JavaDoc[temp.size()];
288         temp.copyInto(fSegments);
289     }
290     /**
291      * @param text a string which contains no wildcard
292      * @param start the starting index in the text for search, inclusive
293      * @param end the stopping point of search, exclusive
294      * @return the starting index in the text of the pattern , or -1 if not found
295      */

296     protected int posIn(String JavaDoc text, int start, int end) {//no wild card in pattern
297
int max= end - fLength;
298
299         if (!fIgnoreCase) {
300             int i= text.indexOf(fPattern, start);
301             if (i == -1 || i > max)
302                 return -1;
303             return i;
304         }
305
306         for (int i= start; i <= max; ++i) {
307             if (text.regionMatches(true, i, fPattern, 0, fLength))
308                 return i;
309         }
310
311         return -1;
312     }
313     /**
314      * @param text a simple regular expression that may only contain '?'(s)
315      * @param start the starting index in the text for search, inclusive
316      * @param end the stopping point of search, exclusive
317      * @param p a simple regular expression that may contains '?'
318      * @return the starting index in the text of the pattern , or -1 if not found
319      */

320     protected int regExpPosIn(String JavaDoc text, int start, int end, String JavaDoc p) {
321         int plen= p.length();
322
323         int max= end - plen;
324         for (int i= start; i <= max; ++i) {
325             if (regExpRegionMatches(text, i, p, 0, plen))
326                 return i;
327         }
328         return -1;
329     }
330
331
332     protected boolean regExpRegionMatches(String JavaDoc text, int tStart, String JavaDoc p, int pStart, int plen) {
333         while (plen-- > 0) {
334             char tchar= text.charAt(tStart++);
335             char pchar= p.charAt(pStart++);
336
337             /* process wild cards */
338             if (!fIgnoreWildCards) {
339                 /* skip single wild cards */
340                 if (pchar == fSingleWildCard) {
341                     continue;
342                 }
343             }
344             if (pchar == tchar)
345                 continue;
346             if (fIgnoreCase) {
347                 if (Character.toUpperCase(tchar) == Character.toUpperCase(pchar))
348                     continue;
349                 // comparing after converting to upper case doesn't handle all cases;
350
// also compare after converting to lower case
351
if (Character.toLowerCase(tchar) == Character.toLowerCase(pchar))
352                     continue;
353             }
354             return false;
355         }
356         return true;
357     }
358     /**
359      * @param text the string to match
360      * @param start the starting index in the text for search, inclusive
361      * @param end the stopping point of search, exclusive
362      * @param p a string that has no wildcard
363      * @return the starting index in the text of the pattern , or -1 if not found
364      */

365     protected int textPosIn(String JavaDoc text, int start, int end, String JavaDoc p) {
366
367         int plen= p.length();
368         int max= end - plen;
369
370         if (!fIgnoreCase) {
371             int i= text.indexOf(p, start);
372             if (i == -1 || i > max)
373                 return -1;
374             return i;
375         }
376
377         for (int i= start; i <= max; ++i) {
378             if (text.regionMatches(true, i, p, 0, plen))
379                 return i;
380         }
381
382         return -1;
383     }
384 }
385
Popular Tags