KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > actions > SimpleWildcardTester


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.ui.actions;
12
13 /**
14  * Implements an algorithm for very simple pattern matching in a string.
15  * There is only one feature: "*" may be used at the start or the end of the
16  * pattern to represent "one or more characters".
17  */

18 public final class SimpleWildcardTester {
19     /**
20      * Returns whether a string matches a particular pattern.
21      *
22      * @param pattern the input pattern
23      * @param str the string to test
24      * @return <code>true</code> if a match occurs; <code>false</code>otherwise.
25      */

26     public static boolean testWildcard(String JavaDoc pattern, String JavaDoc str) {
27         if (pattern.equals("*")) {//$NON-NLS-1$
28
return true;
29         } else if (pattern.startsWith("*")) {//$NON-NLS-1$
30
if (pattern.endsWith("*")) {//$NON-NLS-1$
31
if (pattern.length() == 2) {
32                     return true;
33                 }
34                 return str.indexOf(pattern.substring(1, pattern.length() - 1)) >= 0;
35             }
36             return str.endsWith(pattern.substring(1));
37         } else if (pattern.endsWith("*")) {//$NON-NLS-1$
38
return str.startsWith(pattern.substring(0, pattern.length() - 1));
39         } else {
40             return str.equals(pattern);
41         }
42     }
43
44     /**
45      * Returns whether a string matches a particular pattern. Both string and
46      * pattern are converted to lower case before pattern matching occurs.
47      *
48      * @param pattern the input pattern
49      * @param str the string to test
50      * @return <code>true</code> if a match occurs; <code>false</code>otherwise.
51      */

52     public static boolean testWildcardIgnoreCase(String JavaDoc pattern, String JavaDoc str) {
53
54         //If str is null there was no extension to test
55
if (str == null) {
56             return false;
57         }
58         pattern = pattern.toLowerCase();
59         str = str.toLowerCase();
60         return testWildcard(pattern, str);
61     }
62 }
63
Popular Tags