Pattern.matches() method in Java Regular Expressions

Java 8Object Oriented ProgrammingProgramming

The java.util.regex.Pattern.matches() method matches the regular expression and the given input. It has two parameters i.e. the regex and the input. It returns true if the regex and the input match and false otherwise.

A program that demonstrates the method Pattern.matches() in Java regular expressions is given as follows:

Example

 Live Demo

import java.util.regex.Pattern;
public class Demo {
   public static void main(String args[]) {
      String regex = "a*b";
      String input = "aaab";
      System.out.println("Regex: " + regex);
      System.out.println("Input: " + input);
      boolean match = Pattern.matches(regex, input);
      System.out.println("\nDoes the regex match with the input? " + match);
   }
}

Output

Regex: a*b
Input: aaab
Does the regex match with the input? true

Now let us understand the above program.

The regex and the input values are printed. Then the Pattern.matches() method matches the regular expression and the given input and the result is printed. A code snippet which demonstrates this is as follows:

String regex = "a*b";
String input = "aaab";
System.out.println("Regex: " + regex);
System.out.println("Input: " + input);
boolean match = Pattern.matches(regex, input);
System.out.println("\nDoes the regex match with the input? " + match);
raja
Published on 19-Feb-2019 11:51:27
Advertisements