1 16 package com.blandware.atleap.common.util; 17 18 import org.apache.oro.text.regex.Pattern; 19 import org.apache.oro.text.regex.Perl5Compiler; 20 import org.apache.oro.text.regex.MalformedPatternException; 21 import org.apache.oro.text.regex.Perl5Substitution; 22 import org.apache.oro.text.regex.Util; 23 import org.apache.oro.text.regex.PatternCompiler; 24 import org.apache.oro.text.regex.Substitution; 25 import org.apache.oro.text.regex.PatternMatcher; 26 import org.apache.oro.text.regex.Perl5Matcher; 27 28 29 38 public class RegExUtil { 39 41 43 50 public static String escapeMetasymbols(String s) { 51 StringBuffer sb = new StringBuffer (); 52 for ( int i = 0; i < s.length(); i++ ) { 53 char c = s.charAt(i); 54 switch ( c ) { 55 case '\\': 56 sb.append("\\\\"); 57 break; 58 case '/': 59 sb.append("\\/"); 60 break; 61 case '.': 62 sb.append("\\."); 63 break; 64 case '(': 65 sb.append("\\("); 66 break; 67 case ')': 68 sb.append("\\)"); 69 break; 70 case '[': 71 sb.append("\\["); 72 break; 73 case ']': 74 sb.append("\\]"); 75 break; 76 case '{': 77 sb.append("\\{"); 78 break; 79 case '}': 80 sb.append("\\}"); 81 break; 82 case '+': 83 sb.append("\\+"); 84 break; 85 case '-': 86 sb.append("\\-"); 87 break; 88 case '*': 89 sb.append("\\*"); 90 break; 91 case '?': 92 sb.append("\\?"); 93 break; 94 case '&': 95 sb.append("\\&"); 96 break; 97 case '|': 98 sb.append("\\|"); 99 break; 100 case '^': 101 sb.append("\\^"); 102 break; 103 case '$': 104 sb.append("\\$"); 105 break; 106 default: 107 sb.append(c); 108 } 109 } 110 return sb.toString(); 111 } 112 113 121 public static String replaceAll(String input, String regEx, String replacement) throws MalformedPatternException { 122 return replaceAll(input, regEx, replacement, Perl5Compiler.DEFAULT_MASK); 123 } 124 125 133 public static String replaceAll(String input, String regEx, String replacement, int options) throws MalformedPatternException { 134 PatternCompiler compiler = new Perl5Compiler(); 135 PatternMatcher matcher = new Perl5Matcher(); 136 Pattern pattern = compiler.compile(regEx, options); 137 Substitution substitution = new Perl5Substitution(replacement); 138 return Util.substitute(matcher, pattern, substitution, input, Util.SUBSTITUTE_ALL); 139 } 140 141 } 142 | Popular Tags |