1 43 44 package org.exolab.jms.selector; 45 46 import org.apache.oro.text.regex.MalformedPatternException; 47 import org.apache.oro.text.regex.Pattern; 48 import org.apache.oro.text.regex.Perl5Compiler; 49 50 51 58 final class RegexpFactory { 59 60 63 private RegexpFactory() { 64 } 65 66 76 public static Pattern create(final String pattern, final Character escape) 77 throws InvalidRegexpException { 78 StringBuffer buff = new StringBuffer (); 79 buff.append('^'); 80 81 for (int i = 0; i < pattern.length(); ++i) { 82 boolean escaped = false; 83 char ch = pattern.charAt(i); 84 if (escape != null && ch == escape.charValue()) { 85 if (++i < pattern.length()) { 86 ch = pattern.charAt(i); 87 escaped = true; 88 } else { 89 throw new InvalidRegexpException(pattern); 90 } 91 } 92 93 switch (ch) { 94 case '_': 95 if (escaped) { 96 buff.append(ch); 97 } else { 98 buff.append('.'); 99 } 100 break; 101 case '%': 102 if (escaped) { 103 buff.append(ch); 104 } else { 105 buff.append(".*"); 106 } 107 break; 108 case '.': 109 case '[': 110 case ']': 111 case '\\': 112 case '+': 113 case '?': 114 case '{': 115 case '}': 116 case '$': 117 case '^': 118 case '|': 119 case '(': 120 case ')': 121 buff.append('\\'); 124 buff.append(ch); 125 break; 126 default: 127 buff.append(ch); 128 } 129 } 130 buff.append('$'); 131 132 Pattern result = null; 133 try { 134 Perl5Compiler compiler = new Perl5Compiler(); 135 result = compiler.compile(buff.toString()); 136 } catch (MalformedPatternException exception) { 137 throw new InvalidRegexpException(pattern); 139 } 140 return result; 141 } 142 143 } | Popular Tags |