1 30 31 package com.genimen.djeneric.util; 32 33 public class DjLikeComparator 34 { 35 36 private char _likeChars[]; 37 private int[] _typeOfChar; 38 private int _patternLength; 39 private boolean _ignorecase; 40 41 public DjLikeComparator(String pattern, char escapeChar, boolean ignorecase) 42 { 43 if (ignorecase) 44 { 45 pattern = pattern.toUpperCase(); 46 } 47 48 normalize(pattern, true, escapeChar); 49 _ignorecase = ignorecase; 50 } 51 52 public boolean compare(String value) 53 { 54 if (value == null) 55 { 56 return _patternLength == 0; 57 } 58 59 if (_ignorecase) 60 { 61 value = value.toUpperCase(); 62 } 63 64 return compareAt(value, 0, 0, value.length()); 65 } 66 67 private boolean compareAt(String value, int patternOffset, int valueOffset, int uptoHere) 68 { 69 70 for (; patternOffset < _patternLength; patternOffset++) 71 { 72 switch (_typeOfChar[patternOffset]) 73 { 74 75 case 0 : if ((valueOffset >= uptoHere) || (_likeChars[patternOffset] != value.charAt(valueOffset++))) 77 { 78 return false; 79 } 80 break; 81 82 case 1 : if (valueOffset++ >= uptoHere) 84 { 85 return false; 86 } 87 break; 88 89 case 2 : if (++patternOffset >= _patternLength) 91 { 92 return true; 93 } 94 95 while (valueOffset < uptoHere) 96 { 97 if ((_likeChars[patternOffset] == value.charAt(valueOffset)) 98 && compareAt(value, patternOffset, valueOffset, uptoHere)) 99 { 100 return true; 101 } 102 103 valueOffset++; 104 } 105 106 return false; 107 } 108 } 109 110 if (valueOffset != uptoHere) 111 { 112 return false; 113 } 114 115 return true; 116 } 117 118 private void normalize(String value, boolean supportEscaping, char escapeChar) 119 { 120 121 _patternLength = 0; 122 123 if (value == null) 124 { 125 return; 126 } 127 128 int length = value.length(); 129 130 _likeChars = new char[length]; 131 _typeOfChar = new int[length]; 132 133 boolean isEscaping = false, isPercented = false; 134 135 for (int i = 0; i < length; i++) 136 { 137 char c = value.charAt(i); 138 139 if (isEscaping == false) 140 { 141 if (supportEscaping && (c == escapeChar)) 142 { 143 isEscaping = true; 144 145 continue; 146 } 147 else if (c == '_') 148 { 149 _typeOfChar[_patternLength] = 1; 150 } 151 else if (c == '%') 152 { 153 if (isPercented) 154 { 155 continue; 156 } 157 158 isPercented = true; 159 _typeOfChar[_patternLength] = 2; 160 } 161 else 162 { 163 isPercented = false; 164 } 165 } 166 else 167 { 168 isPercented = false; 169 isEscaping = false; 170 } 171 172 _likeChars[_patternLength++] = c; 173 } 174 175 for (int i = 0; i < _patternLength - 1; i++) 176 { 177 if ((_typeOfChar[i] == 2) && (_typeOfChar[i + 1] == 1)) 178 { 179 _typeOfChar[i] = 1; 180 _typeOfChar[i + 1] = 2; 181 } 182 } 183 } 184 } | Popular Tags |