01: /*
02: * Copyright 2002-2006 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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 pattern, String str) {
36: if (ObjectUtils.nullSafeEquals(pattern, str)
37: || "*".equals(pattern)) {
38: return true;
39: }
40: if (pattern == null || str == null) {
41: return false;
42: }
43: if (pattern.startsWith("*")
44: && pattern.endsWith("*")
45: && str.indexOf(pattern.substring(1,
46: pattern.length() - 1)) != -1) {
47: return true;
48: }
49: if (pattern.startsWith("*")
50: && str.endsWith(pattern.substring(1, pattern.length()))) {
51: return true;
52: }
53: if (pattern.endsWith("*")
54: && str.startsWith(pattern.substring(0,
55: pattern.length() - 1))) {
56: return true;
57: }
58: return false;
59: }
60:
61: /**
62: * Match a String against the given patterns, supporting the following simple
63: * pattern styles: "xxx*", "*xxx" and "*xxx*" matches, as well as direct equality.
64: * @param patterns the patterns to match against
65: * @param str the String to match
66: * @return whether the String matches any of the given patterns
67: */
68: public static boolean simpleMatch(String[] patterns, String str) {
69: if (patterns != null) {
70: for (int i = 0; i < patterns.length; i++) {
71: if (simpleMatch(patterns[i], str)) {
72: return true;
73: }
74: }
75: }
76: return false;
77: }
78:
79: }
|