Java String matches()

In this tutorial, we will learn about the Java String matches() method with the help of examples.

The matches() method checks whether the string matches the given regular expression or not.

Example

class Main {
  public static void main(String[] args) {

    // a regex pattern for
    // four letter string that starts with 'J' and end with 'a'
    String regex = "^J..a$";

System.out.println("Java".matches(regex));
} } // Output: true

Syntax of matches()

The syntax of the string matches() method is:

string.matches(String regex)

Here, string is an object of the String class.


matches() Parameters

The matches() method takes a single parameter.

  • regex - a regular expression

matches() Return Value

  • returns true if the regex matches the string
  • returns false if the regex doesn't match the string

Example 1: Java matches()

class Main {
  public static void main(String[] args) {

    // a regex pattern for
    // five letter string that starts with 'a' and end with 's'
    String regex = "^a...s$";

    System.out.println("abs".matches(regex)); // false
System.out.println("alias".matches(regex)); // true System.out.println("an abacus".matches(regex)); // false
System.out.println("abyss".matches(regex)); // true } }

Here, "^a...s$" is a regex, which means a 5 letter string that starts with a and ends with s.


Example 2: Check for Numbers

// check whether a string contains only numbers

class Main {
  public static void main(String[] args) {

    // a search pattern for only numbers
    String regex = "^[0-9]+$";

    System.out.println("123a".matches(regex)); // false
System.out.println("98416".matches(regex)); // true
System.out.println("98 41".matches(regex)); // false } }

Here, "^[0-9]+$" is a regex, which means only digits.

To learn more about regex, visit Java Regex.

Did you find this article helpful?