English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

matcher() Method in Java Pattern and Example

javajava.util.regexThe package provides various classes to find specific patterns in character sequences.

The package's Pattern class is the compiled representation of the regular expression. This class'smatcher()The method accepts a representation of the input stringCharSequenceThe object of the class, then returns a Matcher object, which matches the given string with the regular expression represented by the current (pattern) object.

Example

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherExample {
   public static void main(String args[]) {
      //Read string value
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string");
      String input = sc.nextLine();
      //Regular expression to find vowels
      String regex = "[aeiou]";
      //Compile the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieve the matcher object
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Given string contains vowels");
      } else {
         System.out.println("Given string does not contain vowels");
      }
   }
}

Output Result

Enter input string
RHYTHM
Given string does not contain vowels