Created
January 15, 2014 01:42
-
-
Save yaoxinghuo/8429303 to your computer and use it in GitHub Desktop.
Java的通配符比较字符串
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Test3 { | |
private static final String PATTERN_LINE_START = "^"; | |
private static final String PATTERN_LINE_END = "$"; | |
private static final char[] META_CHARACTERS = { '$', '^', '[', ']', '(', | |
')', '{', '}', '|', '+', '.', '\\' }; | |
public static void main(String[] args) throws Exception { | |
System.out.println(wildcardMatch("macsynced.??", "macsynced.477")); | |
} | |
public static boolean wildcardMatch(String pattern, String str) { | |
pattern = convertToRegexPattern(pattern); | |
return Pattern.matches(pattern, str); | |
} | |
private static String convertToRegexPattern(String wildcardString) { | |
String result = PATTERN_LINE_START; | |
char[] chars = wildcardString.toCharArray(); | |
for (char ch : chars) { | |
if (Arrays.binarySearch(META_CHARACTERS, ch) >= 0) { | |
result += "\\" + ch; | |
continue; | |
} | |
switch (ch) { | |
case '*': | |
result += ".*"; | |
break; | |
case '?': | |
result += ".{0,1}"; | |
break; | |
default: | |
result += ch; | |
} | |
} | |
result += PATTERN_LINE_END; | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment