What is Validate.matchesPattern in Java?

matchesPattern() is a staticthe methods in Java that can be called without creating an object of the class. method of the Validate class that is used to check whether a given character sequence matches the specified regular expression or not. The method throws an exception if the pattern is not found.

How to import Validate

The definition of Validate can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:


<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
</dependency>

For other versions of the commons-lang package, refer to the Maven Repository.

You can import the Validate class as follows:


import org.apache.commons.lang3.Validate;

Syntax

There are two possible variations of this method.

public static void matchesPattern(CharSequence input, String pattern, String message, Object... values)

// OR

public static void matchesPattern(CharSequence input, String pattern)

Parameters

  • input: The string to check.

  • pattern: The regular expression pattern to compare the string against.

  • message: The exception message to display if the message is not found.

  • values: The optional values for the formatted exception message.

Return value

This method does not return anything.

Code

import org.apache.commons.lang3.Validate;
public class Main{
public static void main(String[] args){
// Example 1
String text = "helloeducative";
String pattern = "[a-zA-Z]*";
Validate.matchesPattern(text, pattern);
// Example 2
String exceptionMessageFormat = "The text '%s' is not matching the regex '%s'";
text = "hello1234";
pattern = "[a-zA-Z]*";
Validate.matchesPattern(text, pattern, exceptionMessageFormat, text, pattern);
}
}

Output

The output of the code will be as follows:

Exception in thread "main" java.lang.IllegalArgumentException: The text 'hello1234' is not matching the regex '[a-zA-Z]*'
	at org.apache.commons.lang3.Validate.matchesPattern(Validate.java:865)
	at Main.main(Main.java:15)

Explanation

Example 1

  • text= "helloeducative"
  • pattern = "[a-zA-Z]*"

Since the regex pattern matches the text, the method does not throw an exception.

Example 2

  • text = "hello1234"
  • pattern = "[a-zA-Z]*"

Since the regex pattern does not match the text, the method throws an IllegalArgumentException exception with "The text 'hello1234' is not matching the regex '[a-zA-Z]*'" as the exception message.

Free Resources

Attributions:
  1. undefined by undefined