VOOZH about

URL: https://www.geeksforgeeks.org/java/string-matches-method-in-java-with-examples/

⇱ String matches() Method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

String matches() Method in Java with Examples

Last Updated : 20 Nov, 2024

In Java, the matches() method in the String class checks if a string matches a specified regular expression. It is useful for validating input patterns and searching within strings.

In this article, we will learn how to use the matches() method effectively in Java with examples to illustrate its functionality.

Example:

In this example, we will check if a string contains only digits.


Output
true

Syntax of matches() method

boolean matches(String regex)

Parameter:

  • regex: The regular expression to match against the string.

Return Type:

  • It returns true if the string matches the regex, otherwise false.

Other Examples of String matches() Method

1. Check for Alphabets using matches()

We will use matches() method to check if a string contains only alphabetic characters.


Output
true


2. Validate an Email Address using matches()

To validate an email addresses, regular expressions can be used with matches() method.


Output
true


3. Check a String Pattern using matches()

To check whether a string follows a specific pattern like combination of digits or letters, we can use matches() method of String class.


Output
true

Points to Remember

  • The matches() method is an efficient way to check if a string is in a specified pattern.
  • By default, it is case-sensitive.
  • Regular expressions are required for defining the patterns.


Comment