1
2
3
4 package net.sourceforge.pmd.util.filter;
5
6 import java.util.regex.Matcher;
7 import java.util.regex.Pattern;
8 import java.util.regex.PatternSyntaxException;
9
10
11
12
13
14
15
16
17
18
19 public class RegexStringFilter implements Filter<String> {
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36 private static final Pattern ENDS_WITH = Pattern
37 .compile("\\^?\\.\\*([^\\\\\\[\\(\\.\\*\\?\\+\\|\\{\\$]+)(?:\\\\?(\\.\\w+))?\\$?");
38
39 protected String regex;
40 protected Pattern pattern;
41 protected String endsWith;
42
43 public RegexStringFilter(String regex) {
44 this.regex = regex;
45 optimize();
46 }
47
48 public String getRegex() {
49 return this.regex;
50 }
51
52 public String getEndsWith() {
53 return this.endsWith;
54 }
55
56 protected void optimize() {
57 final Matcher matcher = ENDS_WITH.matcher(this.regex);
58 if (matcher.matches()) {
59 final String literalPath = matcher.group(1);
60 final String fileExtension = matcher.group(2);
61 if (fileExtension != null) {
62 this.endsWith = literalPath + fileExtension;
63 } else {
64 this.endsWith = literalPath;
65 }
66 } else {
67 try {
68 this.pattern = Pattern.compile(this.regex);
69 } catch (PatternSyntaxException e) {
70
71 }
72 }
73 }
74
75 public boolean filter(String obj) {
76 if (this.endsWith != null) {
77 return obj.endsWith(this.endsWith);
78 } else if (this.pattern != null) {
79 return this.pattern.matcher(obj).matches();
80 } else {
81
82 return false;
83 }
84 }
85
86 @Override
87 public String toString() {
88 return "matches " + this.regex;
89 }
90 }