| 1 3 5 22 23 package edu.neu.ccs.jmk; 24 25 import java.io.*; 26 27 public final class WildCardFilter 28 implements FilenameFilter 29 { 30 private String pattern; 31 private char wildCard; 32 private int[] wildIndex; private String prefix; private String suffix; 35 36 public WildCardFilter(String pattern, char wildCard) { 37 this.pattern = pattern; 38 this.wildCard = wildCard; 39 int wilds = 0; 40 for (int i = 0; i < pattern.length(); i++) 41 if (wildCard == pattern.charAt(i)) 42 wilds++; 43 wildIndex = new int[wilds]; 44 int j = 0; 45 for (int i = 0; j < wilds; i++) 46 if (wildCard == pattern.charAt(i)) 47 wildIndex[j++] = i; 48 if (wilds == 0) { 49 prefix = null; 50 suffix = null; 51 } 52 else { 53 prefix = pattern.substring(0, wildIndex[0]); 54 suffix = pattern.substring(wildIndex[wilds - 1] + 1); 55 } 56 } 57 58 public boolean accept(File dir, String name) { 59 if (wildIndex.length == 0) 60 return pattern.equals(name); 61 else if (!name.startsWith(prefix) 62 || !name.endsWith(suffix)) 63 return false; 64 else if (wildIndex.length == 1) 65 return true; 66 else { 67 int flen = name.length() - suffix.length(); 68 int j = wildIndex[0]; 69 int f = j; for (int i = 1; i < wildIndex.length; i++) { 71 72 73 74 int pstart = j + 1; 75 j = wildIndex[i]; 76 int plen = j - pstart; 77 for (;;) { if (plen + f > flen) 79 return false; 80 81 else if (name.regionMatches(f, pattern, pstart, plen)) 82 break; 83 else 84 f++; 85 } 86 f += plen; 87 } 88 return true; 89 } 90 } 91 92 static private void test(String pattern, String file) { 94 WildCardFilter f = new WildCardFilter(pattern, '*'); 95 String match = f.accept(null, file) ? "matches" : "does not match"; 96 System.out.println("String \"" + file + "\" " + match + 97 " pattern \"" + pattern + "\"."); 98 } 99 100 public static void main(String args[]) { 101 if (args.length == 2) 102 test(args[0], args[1]); 103 else { 104 test("*", "toto"); 105 test("toto.java", "tutu.java"); 106 test("12345", "1234"); 107 test("1234", "12345"); 108 test("*f", ""); 109 test("***", "toto"); 110 test("*.java", "toto."); 111 test("*.java", "toto.jav"); 112 test("*.java", "toto.java"); 113 test("abc*", ""); 114 test("a*c", "abbbbbccccc"); 115 test("abc*xyz", "abcxxxyz"); 116 test("*xyz", "abcxxxyz"); 117 test("abc**xyz", "abcxxxyz"); 118 test("abc**x", "abcxxx"); 119 test("*a*b*c**x", "aaabcxxx"); 120 test("abc*x*yz", "abcxxxyz"); 121 test("abc*x*yz*", "abcxxxyz"); 122 test("a*b*c*x*yf*z*", "aabbccxxxeeyffz"); 123 test("a*b*c*x*yf*zze", "aabbccxxxeeyffz"); 124 test("a*b*c*x*yf*ze", "aabbccxxxeeyffz"); 125 test("a*b*c*x*yf*ze", "aabbccxxxeeyfze"); 126 test("*LogServerInterface*.java", "_LogServerInterfaceImpl.java"); 127 test("abc*xyz", "abcxyxyz"); 128 } 129 } 130 } 131 | Popular Tags |