1 /*
2 * Copyright 2018 SPF4J.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.spf4j.test.matchers;
17
18 import java.util.regex.Pattern;
19
20 import org.hamcrest.Description;
21 import org.hamcrest.Factory;
22 import org.hamcrest.Matcher;
23 import org.hamcrest.TypeSafeMatcher;
24
25 /**
26 * @author Zoltan Farkas
27 */
28 public final class PatternMatcher extends TypeSafeMatcher<String> {
29
30 private final Pattern pattern;
31
32 private PatternMatcher(final Pattern pattern) {
33 this.pattern = pattern;
34 }
35
36 @Override
37 protected boolean matchesSafely(final String item) {
38 return pattern.matcher(item).matches();
39 }
40
41 @Override
42 public void describeTo(final Description description) {
43 description.appendText("a string matching the pattern '" + pattern + "'");
44 }
45
46 /**
47 * Creates a matcher of {@link String} that matches when the examined string exactly matches the given
48 * {@link Pattern}.
49 */
50 @Factory
51 public static Matcher<String> matchesPattern(final Pattern pattern) {
52 return new PatternMatcher(pattern);
53 }
54
55 /**
56 * Creates a matcher of {@link String} that matches when the examined string exactly matches the given regular
57 * expression, treated as a {@link Pattern}.
58 */
59 @Factory
60 public static Matcher<String> matchesPattern(final String regex) {
61 return new PatternMatcher(Pattern.compile(regex));
62 }
63 }