Skip to content

Instantly share code, notes, and snippets.

@yaoxinghuo
Created January 15, 2014 01:42
Show Gist options
  • Save yaoxinghuo/8429303 to your computer and use it in GitHub Desktop.
Save yaoxinghuo/8429303 to your computer and use it in GitHub Desktop.
Java的通配符比较字符串
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