Pattern matcher() method in Java with examples

JavaObject Oriented ProgrammingProgramming

The java.util.regex package of java provides various classes to find particular patterns in character sequences.

The pattern class of this package is a compiled representation of a regular expression. The matcher() method of this class accepts an object of the CharSequence class representing the input string and, returns a Matcher object which matches the given string to 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[]) {
      //Reading 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]";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving 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

Enter input string
RHYTHM
Given string does not contain vowels
raja
Published on 20-Nov-2019 05:38:52
Advertisements