|
| 1 | +/** |
| 2 | + * |
| 3 | + */ |
| 4 | +package org.hamcrest.core; |
| 5 | + |
| 6 | +import java.util.regex.Pattern; |
| 7 | + |
| 8 | +import org.hamcrest.Description; |
| 9 | +import org.hamcrest.Matcher; |
| 10 | +import org.hamcrest.TypeSafeDiagnosingMatcher; |
| 11 | + |
| 12 | +/** |
| 13 | + * @author borettim |
| 14 | + * @author sf105 |
| 15 | + * |
| 16 | + */ |
| 17 | +public class StringRegularExpression extends TypeSafeDiagnosingMatcher<String> { |
| 18 | + |
| 19 | + protected StringRegularExpression(Pattern pattern) { |
| 20 | + this.pattern = pattern; |
| 21 | + } |
| 22 | + |
| 23 | + private Pattern pattern; |
| 24 | + |
| 25 | + @Override |
| 26 | + public void describeTo(Description description) { |
| 27 | + description.appendText("a string matching the pattern ").appendValue(pattern); |
| 28 | + } |
| 29 | + |
| 30 | + @Override |
| 31 | + protected boolean matchesSafely(String actual, Description mismatchDescription) { |
| 32 | + if (!pattern.matcher(actual).matches()) { |
| 33 | + mismatchDescription.appendText("the string was ").appendValue(actual); |
| 34 | + return false; |
| 35 | + } |
| 36 | + return true; |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * Validate a string with a {@link java.util.regex.Pattern}. |
| 41 | + * |
| 42 | + * <pre> |
| 43 | + * assertThat("abc", matchesRegex(Pattern.compile("ˆ[a-z]$")); |
| 44 | + * </pre> |
| 45 | + * |
| 46 | + * @param pattern |
| 47 | + * the pattern to be used. |
| 48 | + * @return The matcher. |
| 49 | + */ |
| 50 | + public static Matcher<String> matchesRegex(Pattern pattern) { |
| 51 | + return new StringRegularExpression(pattern); |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * Validate a string with a regex. |
| 56 | + * |
| 57 | + * <pre> |
| 58 | + * assertThat("abc", matchesRegex("ˆ[a-z]+$")); |
| 59 | + * </pre> |
| 60 | + * |
| 61 | + * @param regex |
| 62 | + * The regex to be used for the validation. |
| 63 | + * @return The matcher. |
| 64 | + */ |
| 65 | + public static Matcher<String> matchesRegex(String regex) { |
| 66 | + return matchesRegex(Pattern.compile(regex)); |
| 67 | + } |
| 68 | +} |
0 commit comments