Java .matches()
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.
Syntax
string.matches(regex)
- The
.matches()method returns a boolean value.- The parameter
regexis a given regular expression that the string is compared to. - This method only returns
truefor complete matches, it will not return ‘true’ for a subset of characters.
- The parameter
Example
The .matches() method is showcased in the following example:
\\ Example.javaclass 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:
falsetruefalsetrue
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve 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