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 this code listing:

package example.regex; 

public class StringMatches
{
public static void main(String[] args)
{
boolean result;
String regex;
String input = "Sky is blue"; // First regex
regex = "\b(red|blue|green)\b";
result = input.matches(regex);
System.out.printf("Match result: %s%n", result);
// prints false

// Second regex
regex = ".*\b(red|blue|green)\b.*";
result = input.matches(regex);
System.out.printf("Match result: %s%n", result);
// prints true
}
}

A few points about this regex are as follows:

  • Alternation (red|blue|green) is being used to match any of the allowed colors
  • The first regex fails to match because we are only matching the allowed colors using alternation but are not matching the text on either side of the alternation
  • The second regex succeeds as we are using . * on both sides of the alternation to match any text before and after the allowed colors in the input text
  • We are also using the word, boundary assertions, around our alternation expression to ensure that we match complete words only

To verify that the given input starts and ends with an English letter while allowing digits, letters, underscores, and hyphens in the middle, we can use the following regular expression in the matches() method:

input.matches("[a-zA-Z][a-zA-Z0-9_-]*[a-zA-Z]"); 

Else, we can also use the predefined class, w:

input.matches("[a-zA-Z][w-]*[a-zA-Z]"); 

In addition, we can use the modifier, (?i):

input.matches("(?i)[a-z][w-]*[a-z]"); 

To verify that the input contains six to nine digits, use the following:

input.matches("\d{6,9}"); 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.229.111