Pattern.matches() method in Java Regular Expressions


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("
Does 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("
Does the regex match with the input? " + match);

Updated on: 30-Jul-2019

132 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements