Skip to content

Instantly share code, notes, and snippets.

@petitviolet
Created August 5, 2015 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petitviolet/823c05d903ee14f51327 to your computer and use it in GitHub Desktop.
Save petitviolet/823c05d903ee14f51327 to your computer and use it in GitHub Desktop.
Regex Matcher for JUnit4 assertThat
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class RegexStringMatcher extends BaseMatcher {
private final Pattern mExpectedPattern;
public RegexStringMatcher(String expected) {
mExpectedPattern = Pattern.compile(expected);
}
public static RegexStringMatcher isMatch(String expected) {
return new RegexStringMatcher(expected);
}
@Override
public boolean matches(Object actual) {
String actualStr = (String) actual;
Matcher matcher = mExpectedPattern.matcher(actualStr);
return matcher.find();
}
@Override
public void describeTo(Description description) {
description.appendText("pattern: ").appendText(mExpectedPattern.pattern());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment