blob: b48c1474cabb0ea0e420ec010420a9d1573c9259 [file] [log] [blame]
Stuart McCullochbb014372012-06-07 21:57:32 +00001package aQute.libg.glob;
2
Stuart McCulloch2286f232012-06-15 13:27:53 +00003import java.util.regex.*;
Stuart McCullochbb014372012-06-07 21:57:32 +00004
5public class Glob {
6
Stuart McCulloch2286f232012-06-15 13:27:53 +00007 private final String glob;
8 private final Pattern pattern;
9
Stuart McCullochbb014372012-06-07 21:57:32 +000010 public Glob(String globString) {
11 this.glob = globString;
12 this.pattern = Pattern.compile(convertGlobToRegEx(globString));
13 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000014
Stuart McCullochbb014372012-06-07 21:57:32 +000015 public Matcher matcher(CharSequence input) {
16 return pattern.matcher(input);
17 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000018
Stuart McCullochbb014372012-06-07 21:57:32 +000019 @Override
20 public String toString() {
21 return glob;
22 }
23
24 private static String convertGlobToRegEx(String line) {
25 line = line.trim();
26 int strLen = line.length();
27 StringBuilder sb = new StringBuilder(strLen);
28 // Remove beginning and ending * globs because they're useless
29 if (line.startsWith("*")) {
30 line = line.substring(1);
31 strLen--;
32 }
33 if (line.endsWith("*")) {
34 line = line.substring(0, strLen - 1);
35 strLen--;
36 }
37 boolean escaping = false;
38 int inCurlies = 0;
39 for (char currentChar : line.toCharArray()) {
40 switch (currentChar) {
Stuart McCulloch2286f232012-06-15 13:27:53 +000041 case '*' :
42 if (escaping)
43 sb.append("\\*");
44 else
45 sb.append(".*");
Stuart McCullochbb014372012-06-07 21:57:32 +000046 escaping = false;
Stuart McCulloch2286f232012-06-15 13:27:53 +000047 break;
48 case '?' :
49 if (escaping)
50 sb.append("\\?");
51 else
52 sb.append('.');
53 escaping = false;
54 break;
55 case '.' :
56 case '(' :
57 case ')' :
58 case '+' :
59 case '|' :
60 case '^' :
61 case '$' :
62 case '@' :
63 case '%' :
64 sb.append('\\');
65 sb.append(currentChar);
66 escaping = false;
67 break;
68 case '\\' :
69 if (escaping) {
70 sb.append("\\\\");
71 escaping = false;
72 } else
73 escaping = true;
74 break;
75 case '{' :
76 if (escaping) {
77 sb.append("\\{");
78 } else {
79 sb.append('(');
80 inCurlies++;
81 }
82 escaping = false;
83 break;
84 case '}' :
85 if (inCurlies > 0 && !escaping) {
86 sb.append(')');
87 inCurlies--;
88 } else if (escaping)
89 sb.append("\\}");
90 else
91 sb.append("}");
92 escaping = false;
93 break;
94 case ',' :
95 if (inCurlies > 0 && !escaping) {
96 sb.append('|');
97 } else if (escaping)
98 sb.append("\\,");
99 else
100 sb.append(",");
101 break;
102 default :
103 escaping = false;
104 sb.append(currentChar);
Stuart McCullochbb014372012-06-07 21:57:32 +0000105 }
106 }
107 return sb.toString();
108 }
109}