1/* 2 * Copyright 2008 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 */ 16package org.mockftpserver.core.util; 17 18/** 19 * Contains static utility methods related to pattern-matching and regular expressions. 20 * 21 * @author Chris Mair 22 * @version $Revision$ - $Date$ 23 */ 24public class PatternUtil { 25 26 /** 27 * Return true if the specified String contains one or more wildcard characters ('?' or '*') 28 * 29 * @param string - the String to check 30 * @return true if the String contains wildcards 31 */ 32 public static boolean containsWildcards(String string) { 33 return string.indexOf("*") != -1 || string.indexOf("?") != -1; 34 } 35 36 /** 37 * Convert the specified String, optionally containing wildcards (? or *), to a regular expression String 38 * 39 * @param stringWithWildcards - the String to convert, optionally containing wildcards (? or *) 40 * @return an equivalent regex String 41 * @throws AssertionError - if the stringWithWildcards is null 42 */ 43 public static String convertStringWithWildcardsToRegex(String stringWithWildcards) { 44 Assert.notNull(stringWithWildcards, "stringWithWildcards"); 45 46 StringBuffer result = new StringBuffer(); 47 for (int i = 0; i < stringWithWildcards.length(); i++) { 48 char ch = stringWithWildcards.charAt(i); 49 switch (ch) { 50 case '*': 51 result.append(".*"); 52 break; 53 case '?': 54 result.append('.'); 55 break; 56 case '$': 57 case '|': 58 case '[': 59 case ']': 60 case '(': 61 case ')': 62 case '.': 63 case ':': 64 case '{': 65 case '}': 66 case '\\': 67 case '^': 68 case '+': 69 result.append('\\'); 70 result.append(ch); 71 break; 72 default: 73 result.append(ch); 74 } 75 } 76 return result.toString(); 77 } 78 79 /** 80 * Private constructor to prevent instantiation. All members are static. 81 */ 82 private PatternUtil() { 83 } 84 85} 86