1 22 package org.jboss.mq.selectors; 23 24 import java.util.regex.Pattern ; 25 26 36 public class RegExp 37 { 38 protected Pattern re; 39 40 public RegExp (String pattern, Character escapeChar) 41 throws Exception 42 { 43 String pat = adjustPattern(pattern, escapeChar); 44 re = Pattern.compile(pat); 45 } 46 47 public boolean isMatch (Object target) 48 { 49 String str = target != null ? target.toString() : ""; 50 return re.matcher(str).matches(); 51 } 52 53 protected String adjustPattern (String pattern, Character escapeChar) 54 throws Exception 55 { 56 57 int patternLen = pattern.length(); 59 StringBuffer REpattern = new StringBuffer (patternLen + 10); 60 boolean useEscape = (escapeChar != null); 61 char escape = Character.UNASSIGNED; 62 if (useEscape) { 63 escape = escapeChar.charValue(); 64 } 65 66 REpattern.append ('^'); 67 68 for ( int i = 0; i < patternLen; i++ ) { 69 boolean escaped = false; 70 char c = pattern.charAt( i ); 71 72 if ( useEscape && escape == c ) { 73 i++; 74 if ( i < patternLen ) { 75 escaped = true; 76 c = pattern.charAt( i ); 77 } else { 78 throw new Exception ( "LIKE ESCAPE: Bad use of escape character" ); 79 } 80 } 81 82 switch ( c ) { 85 case '_': 86 if ( escaped ) { 87 REpattern.append( c ); 88 } else { 89 REpattern.append( '.' ); 90 } 91 break; 92 case '%': 93 if ( escaped ) { 94 REpattern.append( c ); 95 } else { 96 REpattern.append( ".*" ); 97 } 98 break; 99 case '*': 100 case '.': 101 case '\\': 102 case '^': 103 case '$': 104 case '[': 105 case ']': 106 case '(': 107 case ')': 108 case '+': 109 case '?': 110 case '{': 111 case '}': 112 case '|': 113 REpattern.append( "\\"); 114 REpattern.append ( c ); 115 break; 116 default: 117 REpattern.append( c ); 118 break; 119 } 120 } 121 122 REpattern.append( '$' ); 123 return REpattern.toString(); 124 } 125 } 126 127 | Popular Tags |