O'Reilly logo

Java 9 Regular Expressions by Anubhava Srivastava

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Example of the matches method

Let's look at a few examples to understand this method better.

The following code snippet using the matches method will return false:

"1234".matches("\\d"); 

It is because the matches method attempts to apply a given regex against the entire input and effectively runs this code as:

"1234".matches("^\\d$"); 

This will obviously fail as we have three digits in the input, not just one.

The code that matches the string "1234" and the call to the matches()method that returns true will use the quantifier + or * after \\d. Therefore, the following two method calls will return true:

"1234".matches("\\d+"); "1234".matches("\\d+"); 

To validate a given string that contains the colors red, blue, or green, we shall use ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required