1 package webman.stager; 2 3 import java.io.*; 4 import java.util.*; 5 6 12 public class FileNameMatcher 13 { 14 Hashtable results = new Hashtable(); 15 16 public FileNameMatcher() 17 { 18 Hashtable h = new Hashtable(); 20 results.put("*", h); 21 h.put("", new String []{""}); 22 } 23 24 31 public String getMatchResult(String pattern, String filename, int n) 32 { 33 Hashtable h = (Hashtable)results.get(pattern); 35 if ( h == null && !matches(pattern, filename) ) 36 { 37 return null; 38 } 39 else 40 { 41 h = (Hashtable)results.get(pattern); 42 } 43 String [] res = (String [])h.get(filename); 44 if ( res == null && !matches(pattern, filename) ) 45 { 46 return null; 47 } 48 else 49 { 50 res = (String [])h.get(filename); 51 } 52 if ( n < 0 || n >= res.length ) 54 { 55 return null; 56 } 57 return res[n]; 58 } 59 60 63 public boolean matches(String pattern, String filename) 64 { 65 filename = filename.trim(); 67 Hashtable h = (Hashtable)results.get(pattern); 69 if ( h != null && h.get(filename) != null ) 70 { 71 return true; 72 } 73 int i; 75 while ( (i = pattern.indexOf("**")) >= 0 ) 76 { 77 pattern = pattern.substring(0, i) + pattern.substring(i + 1, pattern.length()); 78 } 79 int index = 0; 81 int num = 0; 82 while ( (i = pattern.indexOf('*', index)) >= 0 ) 83 { 84 index = i + 1; 85 num++; 86 } 87 index = 0; 88 while ( (i = pattern.indexOf('?', index)) >= 0 ) 89 { 90 index = i + 1; 91 num++; 92 } 93 String [] result = new String [num]; 95 96 if ( matches(pattern.toCharArray(), 0, filename.toCharArray(), 0, result, 0) ) 97 { 98 h = (Hashtable)results.get(pattern); 99 if ( h == null ) 100 { 101 h = new Hashtable(); 102 } 103 h.put(filename, result); 104 results.put(pattern, h); 105 return true; 106 } 107 return false; 108 } 109 110 boolean matches(char[] t, int tp, char[] name, int np, String [] res, int rp) 111 { 112 if ( tp == t.length && np == name.length ) 114 { 115 return true; 117 } 118 if ( tp == t.length ) 120 { 121 return false; 122 } 123 if ( np == name.length ) 125 { 126 return false; 127 } 128 129 130 int next_tp = tp + 1; 132 if ( t[tp] == '*' ) 133 { 134 for ( int i = np; i <= name.length; i++ ) 137 { 138 if ( matches(t, next_tp, name, i, res, rp + 1) ) 139 { 140 res[rp] = (new String (name)).substring(np, i); 141 return true; 142 } 143 } 144 return false; 145 } 146 else if ( t[tp] == '?' ) 147 { 148 if ( matches(t, next_tp, name, np + 1, res, rp + 1) ) 150 { 151 res[rp] = (new String (name)).substring(np, np + 1); 152 return true; 153 } 154 return false; 155 } 156 else 157 { 158 return (t[tp] == name[np] && matches(t, next_tp, name, np + 1, res, rp)); 160 } 161 } 162 } | Popular Tags |