org.hamcrest.core.StringRegularExpression Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of hamcrest Show documentation
Show all versions of hamcrest Show documentation
Core API and libraries of hamcrest matcher framework.
package org.hamcrest.core;
import java.util.regex.Pattern;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeDiagnosingMatcher;
/**
* @author borettim
* @author sf105
*
*/
public class StringRegularExpression extends TypeSafeDiagnosingMatcher {
protected StringRegularExpression(Pattern pattern) {
this.pattern = pattern;
}
private Pattern pattern;
@Override
public void describeTo(Description description) {
description.appendText("a string matching the pattern ").appendValue(pattern);
}
@Override
protected boolean matchesSafely(String actual, Description mismatchDescription) {
if (!pattern.matcher(actual).matches()) {
mismatchDescription.appendText("the string was ").appendValue(actual);
return false;
}
return true;
}
/**
* Creates a matcher that checks if the examined string matches a specified {@link java.util.regex.Pattern}.
*
*
* assertThat("abc", matchesRegex(Pattern.compile("ˆ[a-z]$"));
*
*
* @param pattern
* the pattern to be used.
* @return The matcher.
*/
public static Matcher matchesRegex(Pattern pattern) {
return new StringRegularExpression(pattern);
}
/**
* Creates a matcher that checks if the examined string matches a specified regex.
*
*
* assertThat("abc", matchesRegex("ˆ[a-z]+$"));
*
*
* @param regex
* The regex to be used for the validation.
* @return The matcher.
*/
public static Matcher matchesRegex(String regex) {
return matchesRegex(Pattern.compile(regex));
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy