01: /*******************************************************************************
02: * Copyright (c) 2000, 2005 IBM Corporation and others.
03: * All rights reserved. This program and the accompanying materials
04: * are made available under the terms of the Eclipse Public License v1.0
05: * which accompanies this distribution, and is available at
06: * http://www.eclipse.org/legal/epl-v10.html
07: *
08: * Contributors:
09: * IBM Corporation - initial API and implementation
10: *******************************************************************************/package org.eclipse.pde.internal.core.util;
11:
12: import java.util.regex.Pattern;
13:
14: public class PatternConstructor {
15: private static final Pattern PATTERN_BACK_SLASH = Pattern
16: .compile("\\\\"); //$NON-NLS-1$
17:
18: private static final Pattern PATTERN_QUESTION = Pattern
19: .compile("\\?"); //$NON-NLS-1$
20:
21: private static final Pattern PATTERN_STAR = Pattern.compile("\\*"); //$NON-NLS-1$
22:
23: private static final Pattern PATTERN_LBRACKET = Pattern
24: .compile("\\("); //$NON-NLS-1$
25:
26: private static final Pattern PATTERN_RBRACKET = Pattern
27: .compile("\\)"); //$NON-NLS-1$
28:
29: /*
30: * Converts user string to regular expres '*' and '?' to regEx variables.
31: *
32: */
33: private static String asRegEx(String pattern, boolean group) {
34: // Replace \ with \\, * with .* and ? with .
35: // Quote remaining characters
36: String result1 = PATTERN_BACK_SLASH.matcher(pattern)
37: .replaceAll("\\\\E\\\\\\\\\\\\Q"); //$NON-NLS-1$
38: String result2 = PATTERN_STAR.matcher(result1).replaceAll(
39: "\\\\E.*\\\\Q"); //$NON-NLS-1$
40: String result3 = PATTERN_QUESTION.matcher(result2).replaceAll(
41: "\\\\E.\\\\Q"); //$NON-NLS-1$
42: if (group) {
43: result3 = PATTERN_LBRACKET.matcher(result3).replaceAll(
44: "\\\\E(\\\\Q"); //$NON-NLS-1$
45: result3 = PATTERN_RBRACKET.matcher(result3).replaceAll(
46: "\\\\E)\\\\Q"); //$NON-NLS-1$
47: }
48: return "\\Q" + result3 + "\\E"; //$NON-NLS-1$ //$NON-NLS-2$
49: }
50:
51: /**
52: * Creates a regular expression pattern from the pattern string (which is
53: * our old 'StringMatcher' format).
54: *
55: * @param pattern
56: * The search pattern
57: * @param isCaseSensitive
58: * Set to <code>true</code> to create a case insensitve pattern
59: * @return The created pattern
60: */
61: public static Pattern createPattern(String pattern,
62: boolean isCaseSensitive) {
63: if (isCaseSensitive)
64: return Pattern.compile(asRegEx(pattern, false));
65: return Pattern.compile(asRegEx(pattern, false),
66: Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
67: }
68:
69: public static Pattern createGroupedPattern(String pattern,
70: boolean isCaseSensitive) {
71: if (isCaseSensitive)
72: return Pattern.compile(asRegEx(pattern, true));
73: return Pattern.compile(asRegEx(pattern, true),
74: Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
75: }
76:
77: private PatternConstructor() {
78: }
79: }
|