Java String matches()

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

Example


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()

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

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

To learn more about regex, visit Java Regex.