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:


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


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 ...

Get Java 9 Regular Expressions now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.