Java .matches()

CaupolicanDiaz's avatar
Published Feb 14, 2023Updated Mar 18, 2023
Contribute to Docs

The .matches() method checks whether a string matches a given regular expression, returning true or false.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours

Syntax

string.matches(regex)
  • The .matches() method returns a boolean value.
    • The parameter regex is a given regular expression that the string is compared to.
    • This method only returns true for complete matches, it will not return ‘true’ for a subset of characters.

Example

The .matches() method is showcased in the following example:

\\ Example.java
class Example {
public static void main(String[] args) {
// a regex that matches 'hello' or 'goodbye'
String regex = "Hello|Goodbye";
System.out.println("Hello World".matches(regex));
System.out.println("Goodbye".matches(regex));
System.out.println("Hello, Goodbye".matches(regex));
System.out.println("Hello".matches(regex));
}
}

This example results in the following output:

false
true
false
true

All contributors

Contribute to Docs

Learn Java on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours