01 package net.sourceforge.pmd.lang.java.rule.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 final class RegexHelper {
16
17 /**
18 * Default private empty constructors
19 */
20 private RegexHelper() {}
21
22 /**
23 * Compiles a list of regex into a list of patterns.
24 * @param list the regex list
25 * @return the pattern list
26 */
27 public static List<Pattern> compilePatternsFromList(List<String> list) {
28 List<Pattern> patterns;
29 if (list != null && !list.isEmpty()) {
30 patterns = new ArrayList<Pattern>(list.size());
31 for (String stringPattern : list) {
32 if ( stringPattern != null && ! "".equals(stringPattern) ) {
33 patterns.add(Pattern.compile(stringPattern));
34 }
35 }
36 } else {
37 patterns = new ArrayList<Pattern>(0);
38 }
39 return patterns;
40 }
41
42 /**
43 * Simple commodity method (also designed to increase readability of source code,
44 * and to decrease import in the calling class).
45 * Provide a pattern and a subject, it'll do the proper matching.
46 *
47 * @param pattern a compiled regex pattern
48 * @param subject a String to match
49 * @return {@code true} if there is a match; {@code false} otherwise
50 */
51 public static boolean isMatch(Pattern pattern,String subject) {
52 if ( subject != null && ! "".equals(subject) ) {
53 Matcher matcher = pattern.matcher(subject);
54 if (matcher.find()) {
55 return true;
56 }
57 }
58 return false;
59 }
60
61
62 }
|