com.lyncode.test.matchers.string.PatternMatcher Maven / Gradle / Ivy
package com.lyncode.test.matchers.string;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import java.util.regex.Pattern;
/**
* Tests if the argument is a {@link CharSequence} that matches a regular expression.
*/
public class PatternMatcher extends TypeSafeMatcher {
/**
* Creates a matcher that matches if the examined {@link CharSequence} matches the specified
* regular expression.
*
* For example:
* assertThat("myStringOfNote", pattern("[0-9]+"))
*
* @param regex the regular expression that the returned matcher will use to match any examined {@link CharSequence}
*/
@Factory
public static Matcher pattern(String regex) {
return pattern(Pattern.compile(regex));
}
/**
* Creates a matcher that matches if the examined {@link CharSequence} matches the specified
* {@link java.util.regex.Pattern}.
*
* For example:
* assertThat("myStringOfNote", Pattern.compile("[0-9]+"))
*
* @param pattern the pattern that the returned matcher will use to match any examined {@link CharSequence}
*/
@Factory
public static Matcher pattern(Pattern pattern) {
return new PatternMatcher(pattern);
}
private final Pattern pattern;
public PatternMatcher(Pattern pattern) {
this.pattern = pattern;
}
@Override
public boolean matchesSafely(CharSequence item) {
return pattern.matcher(item).matches();
}
@Override
public void describeMismatchSafely(CharSequence item, org.hamcrest.Description mismatchDescription) {
mismatchDescription.appendText("was \"").appendText(String.valueOf(item)).appendText("\"");
}
@Override
public void describeTo(org.hamcrest.Description description) {
description.appendText("a string with pattern \"").appendText(String.valueOf(pattern)).appendText("\"");
}
}