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