Home | History | Annotate | Download | only in text
      1 package org.hamcrest.text;
      2 
      3 import org.hamcrest.Description;
      4 import org.hamcrest.Matcher;
      5 import org.hamcrest.TypeSafeMatcher;
      6 
      7 import java.util.regex.Pattern;
      8 
      9 public class MatchesPattern extends TypeSafeMatcher<String> {
     10     private final Pattern pattern;
     11 
     12     public MatchesPattern(Pattern pattern) {
     13         this.pattern = pattern;
     14     }
     15 
     16     @Override
     17     protected boolean matchesSafely(String item) {
     18         return pattern.matcher(item).matches();
     19     }
     20 
     21     @Override
     22     public void describeTo(Description description) {
     23         description.appendText("a string matching the pattern '" + pattern + "'");
     24     }
     25 
     26     /**
     27      * Creates a matcher of {@link java.lang.String} that matches when the examined string
     28      * exactly matches the given {@link java.util.regex.Pattern}.
     29      */
     30     public static Matcher<String> matchesPattern(Pattern pattern) {
     31         return new MatchesPattern(pattern);
     32     }
     33 
     34     /**
     35      * Creates a matcher of {@link java.lang.String} that matches when the examined string
     36      * exactly matches the given regular expression, treated as a {@link java.util.regex.Pattern}.
     37      */
     38     public static Matcher<String> matchesPattern(String regex) {
     39         return new MatchesPattern(Pattern.compile(regex));
     40     }
     41 }
     42