matchesPattern()
is a 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.
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;
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)
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.
This method does not return anything.
import org.apache.commons.lang3.Validate;public class Main{public static void main(String[] args){// Example 1String text = "helloeducative";String pattern = "[a-zA-Z]*";Validate.matchesPattern(text, pattern);// Example 2String exceptionMessageFormat = "The text '%s' is not matching the regex '%s'";text = "hello1234";pattern = "[a-zA-Z]*";Validate.matchesPattern(text, pattern, exceptionMessageFormat, text, pattern);}}
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)
text
= "helloeducative"
pattern
= "[a-zA-Z]*"
Since the regex pattern matches the text, the method does not throw an exception.
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