Java String matches() Method Tutorial

In this section, we will learn what the String matches() method is and how to use it in Java.

What is Java String matches() Method?

The Java String matches() method is used to compare a string value against a regular expression pattern and see if that string value matches this pattern.

Note: please check the regular expression section if you don’t know what it is and how it works.

Java matches() Method Syntax:

public boolean matches(String regex)

matches() Method Parameters:

The method takes one argument of type String and that is the given regular expression that we want to compare the target String with.

matches() Method Return Value:

The return value of this method is a Boolean one.

The returned value of this method is `true` if they match and `false` otherwise.

matches() Method Exceptions:

This method does not throw an exception.

Example: using String matches() method

public class Simple {

    public static void main(String args[]) {
        String Str = "Always increase your knowledge.";

        System.out.print("Return Value :" );
        System.out.println(Str.matches("(.*)increase(.*)"));

        System.out.print("Return Value :" );
        System.out.println(Str.matches("increase"));

        System.out.print("Return Value :" );
        System.out.println(Str.matches("Always(.*)"));
    }
}

Output:

Return Value :true

Return Value :false

Return Value :true

Leave a Reply