Java.lang Package Classes

Java - String matches() Method



The Java string matches() method is used to check whether the string matches the specified regular expression or not. It returns true if the string matches the given regular expression, else returns false.

Syntax

public boolean matches(String regex)

Parameters

regex Specify the regular expression to which the string is to be matched.

Return Value

Returns true if the string matches the given regular expression, false otherwise.

Exception

Throws PatternSyntaxException, if the regular expression's syntax is invalid.

Example:

In the example below, matches() method is used to check whether the string called MyString matches the specified regular expression.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    String MyString = "Learn Programming with AlphaCodingSkills";
    
    System.out.print("Match Result: "); 
    System.out.println(MyString.matches("(.*)Coding(.*)")); 

    System.out.print("Match Result: "); 
    System.out.println(MyString.matches("Coding(.*)")); 

    System.out.print("Match Result: "); 
    System.out.println(MyString.matches("(.*)Programming(.*)"));  
  }
}

The output of the above code will be:

Match Result: true
Match Result: false
Match Result: true

❮ Java.lang - String