1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package net.sf.statcvs.util;
24
25 import java.util.ArrayList;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.StringTokenizer;
29 import java.util.regex.Pattern;
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48 public class FilePatternMatcher {
49 private final String originalPattern;
50 private final List patterns = new ArrayList();
51
52
53
54
55
56
57 public FilePatternMatcher(final String wildcardPattern) {
58 this.originalPattern = wildcardPattern;
59 final StringTokenizer tokenizer = new StringTokenizer(wildcardPattern, ":;");
60 while (tokenizer.hasMoreTokens()) {
61 patterns.add(Pattern.compile(buildRegex(tokenizer.nextToken())));
62 }
63 }
64
65
66
67
68
69
70 public boolean matches(final String filename) {
71 final Iterator it = patterns.iterator();
72 while (it.hasNext()) {
73 final Pattern regex = (Pattern) it.next();
74 if (regex.matcher(filename).matches()) {
75 return true;
76 }
77 }
78 return false;
79 }
80
81 private String buildRegex(final String wildcardPattern) {
82 String temp = wildcardPattern;
83 temp = temp.replace('\\', '/');
84 if (temp.endsWith("/")) {
85 temp += "**";
86 }
87
88
89
90
91
92 at start with (.*/)? and /** at end with (/.*)?
93 if (temp.startsWith("**/") && temp.endsWith("/**")) {
94 final String inner = temp.substring(3, temp.length() - 3);
95 return "(.*/)?" + buildInnerRegex(inner) + "(/.*)?";
96 }
97 if (temp.startsWith("**/")) {
98 final String inner = temp.substring(3);
99 return "(.*/)?" + buildInnerRegex(inner);
100 }
101 if (temp.endsWith("/**")) {
102 final String inner = temp.substring(0, temp.length() - 3);
103 return buildInnerRegex(inner) + "(/.*)?";
104 }
105 return buildInnerRegex(temp);
106 }
107
108 private String buildInnerRegex(final String wildcardPattern) {
109 )?
110 final int pos = wildcardPattern.indexOf("/**/");
111 if (pos > -1) {
112 final String before = wildcardPattern.substring(0, pos);
113 final String after = wildcardPattern.substring(pos + 4);
114 return buildInnerRegex(before) + "/(.*/)?" + buildInnerRegex(after);
115 }
116
117 return wildcardPattern.replaceAll("\\?", "[^/]").replaceAll("\\*", "[^/]*");
118 }
119
120 public String toString() {
121 return this.originalPattern;
122 }
123 }