View Javadoc

1   package net.sourceforge.pmd.rules.regex;
2   
3   import java.util.ArrayList;
4   import java.util.List;
5   import java.util.regex.Matcher;
6   import java.util.regex.Pattern;
7   
8   /**
9    * 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  	 * 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.size() > 0) {
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  		}
37  		else
38  			patterns = new ArrayList<Pattern>(0);
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  }