KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > util > PatternMatchUtils


1 /*
2  * Copyright 2002-2006 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.springframework.util;
18
19 /**
20  * Utility methods for simple pattern matching, in particular for
21  * Spring's typical "xxx*", "*xxx" and "*xxx*" pattern styles.
22  *
23  * @author Juergen Hoeller
24  * @since 2.0
25  */

26 public abstract class PatternMatchUtils {
27
28     /**
29      * Match a String against the given pattern, supporting the following simple
30      * pattern styles: "xxx*", "*xxx" and "*xxx*" matches, as well as direct equality.
31      * @param pattern the pattern to match against
32      * @param str the String to match
33      * @return whether the String matches the given pattern
34      */

35     public static boolean simpleMatch(String JavaDoc pattern, String JavaDoc str) {
36         if (ObjectUtils.nullSafeEquals(pattern, str) || "*".equals(pattern)) {
37             return true;
38         }
39         if (pattern == null || str == null) {
40             return false;
41         }
42         if (pattern.startsWith("*") && pattern.endsWith("*") &&
43                 str.indexOf(pattern.substring(1, pattern.length() - 1)) != -1) {
44             return true;
45         }
46         if (pattern.startsWith("*") && str.endsWith(pattern.substring(1, pattern.length()))) {
47             return true;
48         }
49         if (pattern.endsWith("*") && str.startsWith(pattern.substring(0, pattern.length() - 1))) {
50             return true;
51         }
52         return false;
53     }
54
55     /**
56      * Match a String against the given patterns, supporting the following simple
57      * pattern styles: "xxx*", "*xxx" and "*xxx*" matches, as well as direct equality.
58      * @param patterns the patterns to match against
59      * @param str the String to match
60      * @return whether the String matches any of the given patterns
61      */

62     public static boolean simpleMatch(String JavaDoc[] patterns, String JavaDoc str) {
63         if (patterns != null) {
64             for (int i = 0; i < patterns.length; i++) {
65                 if (simpleMatch(patterns[i], str)) {
66                     return true;
67                 }
68             }
69         }
70         return false;
71     }
72
73 }
74
Popular Tags