01: package net.sourceforge.pmd.rules.regex;
02:
03: import java.util.ArrayList;
04: import java.util.List;
05: import java.util.regex.Matcher;
06: import java.util.regex.Pattern;
07:
08: /**
09: * A simple helper class to regroup a bunch of method
10: * generally used by rules using regex.
11: *
12: * @author Romain PELISSE, belaran@gmail.com
13: *
14: */
15: public class RegexHelper {
16:
17: /**
18: * Default private empty constructors
19: */
20: private RegexHelper() {
21: }
22:
23: /**
24: * Compiles a list of regex into a list of patterns.
25: * @param list the regex list
26: * @return the pattern list
27: */
28: public static List<Pattern> compilePatternsFromList(
29: List<String> list) {
30: List<Pattern> patterns;
31: if (list != null && list.size() > 0) {
32: patterns = new ArrayList<Pattern>(list.size());
33: for (String stringPattern : list) {
34: if (stringPattern != null && !"".equals(stringPattern)) {
35: patterns.add(Pattern.compile(stringPattern));
36: }
37: }
38: } else
39: patterns = new ArrayList<Pattern>(0);
40: return patterns;
41: }
42:
43: /**
44: * Simple commodity method (also designed to increase readability of source code,
45: * and to decrease import in the calling class).
46: * Provide a pattern and a subject, it'll do the proper matching.
47: *
48: * @param pattern a compiled regex pattern
49: * @param subject a String to match
50: * @return {@code true} if there is a match; {@code false} otherwise
51: */
52: public static boolean isMatch(Pattern pattern, String subject) {
53: if (subject != null && !"".equals(subject)) {
54: Matcher matcher = pattern.matcher(subject);
55: if (matcher.find()) {
56: return true;
57: }
58: }
59: return false;
60: }
61:
62: }
|