• 1.4

Regular Expression Hamcrest Matchers

RegexMatchers is a utility class with static methods that create Hamcrest matchers that can check Strings against regular expressions, as used in unit tests.

You can check if an entire string matches a certain regular expression in the following manner:

import com.jcabi.matchers.RegexMatchers;
import org.hamcrest.MatcherAssert;
public class FooTest {
  @Test
  public void stringMatchesPattern() {
    MatcherAssert.assert(
      "abc123",
      RegexMatchers.matchesPattern("[a-c]+\\d{3}")
    );
  }
}

You may also check if a string contains a substring matching a regular expression, as shown below:

import com.jcabi.matchers.RegexMatchers;
import org.hamcrest.MatcherAssert;
public class FooTest {
  @Test
  public void stringContainsPattern() {
    MatcherAssert.assert(
      "foobar456",
      RegexMatchers.containsPattern("ar45")
    );
  }
}

These dependencies you will need in your pom.xml:

<dependency>
  <groupId>org.hamcrest</groupId>
  <artifactId>hamcrest-library</artifactId>
  <version>1.3</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.hamcrest</groupId>
  <artifactId>hamcrest-core</artifactId>
  <version>1.3</version>
  <scope>test</scope>
</dependency>