Piotr Gabryanczyk’s Blog

Java, Refactoring, AOP, Spring, DDD, TDD, etc.

  • Blogroll

    • I have joined Anti-IF Campaign

Archive for March, 2009

Hamcrest Regex Matcher

Posted by Piotr Gabryanczyk on March 27, 2009

Problem

I could not find a regex matcher in hamcrest, to do ie.
assertThat(selenium.getTitle(), matches("Template T\d{3}"));

It could be that I was not looking well enough or Nat Pryce decided not to include it on purpose. Of’course I saw PatternMatcher, but it lets you build regexes rather then match against them.

Solution

So here you have, enjoy!


public class RegexMatcher extends BaseMatcher{
    private final String regex;

    public RegexMatcher(String regex){
        this.regex = regex;
    }

    public boolean matches(Object o){
        return ((String)o).matches(regex);

    }

    public void describeTo(Description description){
        description.appendText("matches regex=");
    }
    
    public static RegexMatcher matches(String regex){
        return new RegexMatcher(regex);
    }
}

Advertisements

Posted in Uncategorized | 7 Comments »