public class Test { public static void main(String args[]) { String a = "abcdc"; String b = "*a*b*c"; System.out.println(check(a, b)); } //filterStr是以逗號隔開的多個過濾條件 public static boolean check(String str, String filterStr) { String[] filters = filterStr.split(","); for (String filter : filters) { if (checkone(str, filter)) { return true; } } return false; } public static boolean checkone(String str, String filter) { if ("*".equals(String.valueOf(filter.charAt(0)))) { filter = filter.substring(1, filter.length()); String[] f = filter.split("\\*"); if (f.length == 1) { if (filter.endsWith("*")) { if (str.contains(f[0])) { return true; } else { return false; } } else { if (str.endsWith(f[0])) { return true; } else { return false; } } } else { int length = f.length; if (filter.endsWith("*")) { for (int i = 0; i < length; i++) { if (!str.contains(f[i])) { return false; } else { str = str.substring(str.indexOf(f[i]) + f[i].length()); } } return true; } else { for (int i = 0; i < length; i++) { if (i == length - 1) { if (!str.endsWith(f[i])) { return false; } } else { if (!str.contains(f[i])) { return false; } } str = str.substring(str.indexOf(f[i]) + f[i].length()); } return true; } } } else { String[] f = filter.split("\\*"); if (f.length == 1) { if (filter.endsWith("*")) { if (str.startsWith(f[0])) { return true; } else { return false; } } else { if (str.equals(f[0])) { return true; } else { return false; } } } else { int length = f.length; if (filter.endsWith("*")) { for (int i = 0; i < length; i++) { if (i == 0) { if (!str.startsWith(f[i])) { return false; } } else { if (!str.contains(f[i])) { return false; } } str = str.substring(str.indexOf(f[i]) + f[i].length()); } return true; } else { for (int i = 0; i < length; i++) { if (i == 0) { if (!str.startsWith(f[i])) { return false; } } else { if (i == length - 1) { if (!str.endsWith(f[i])) { return false; } } else { if (!str.contains(f[i])) { return false; } } } str = str.substring(str.indexOf(f[i]) + f[i].length()); } return true; } } } } }
下面一種經過正則表達式實現java
public boolean filter(String filename,String filterStr){ String[] fileNameFilters = filterStr.split(","); for(int i=0;i<fileNameFilters.length;i++){ String regex = fileNameFilters[i]; regex = regex.replace(".", "\\."); regex = regex.replace("*", ".*"); Pattern p = Pattern.compile(regex); java.util.regex.Matcher m = p.matcher(filename); if( m.matches()){ return true; } } return false; }