1 11 package org.eclipse.jdt.internal.ui.util; 12 13 import java.util.regex.Pattern ; 14 import java.util.regex.PatternSyntaxException ; 15 16 19 public class PatternConstructor { 20 21 22 private PatternConstructor() { 23 } 25 26 35 public static Pattern createPattern(String pattern, boolean isCaseSensitive, boolean isRegexSearch) throws PatternSyntaxException { 36 if (!isRegexSearch) { 37 pattern= asRegEx(pattern, new StringBuffer ()).toString(); 38 } 39 40 if (!isCaseSensitive) 41 return Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.MULTILINE); 42 43 return Pattern.compile(pattern, Pattern.MULTILINE); 44 } 45 46 55 public static Pattern createPattern(String [] patterns, boolean isCaseSensitive, boolean isRegexSearch) throws PatternSyntaxException { 56 StringBuffer pattern= new StringBuffer (); 57 for (int i= 0; i < patterns.length; i++) { 58 if (i > 0) { 59 pattern.append('|'); 60 } 61 if (isRegexSearch) { 62 pattern.append(patterns[i]); 63 } else { 64 asRegEx(patterns[i], pattern); 65 } 66 } 67 return createPattern(pattern.toString(), isCaseSensitive, true); 68 } 69 70 71 75 private static StringBuffer asRegEx(String stringMatcherPattern, StringBuffer out) { 76 boolean escaped= false; 77 boolean quoting= false; 78 79 int i= 0; 80 while (i < stringMatcherPattern.length()) { 81 char ch= stringMatcherPattern.charAt(i++); 82 83 if (ch == '*' && !escaped) { 84 if (quoting) { 85 out.append("\\E"); quoting= false; 87 } 88 out.append(".*"); escaped= false; 90 continue; 91 } else if (ch == '?' && !escaped) { 92 if (quoting) { 93 out.append("\\E"); quoting= false; 95 } 96 out.append("."); escaped= false; 98 continue; 99 } else if (ch == '\\' && !escaped) { 100 escaped= true; 101 continue; 102 103 } else if (ch == '\\' && escaped) { 104 escaped= false; 105 if (quoting) { 106 out.append("\\E"); quoting= false; 108 } 109 out.append("\\\\"); continue; 111 } 112 113 if (!quoting) { 114 out.append("\\Q"); quoting= true; 116 } 117 if (escaped && ch != '*' && ch != '?' && ch != '\\') 118 out.append('\\'); 119 out.append(ch); 120 escaped= ch == '\\'; 121 122 } 123 if (quoting) 124 out.append("\\E"); 126 return out; 127 } 128 129 } 130 | Popular Tags |