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

Java Matcher usePattern() method with example

The java.util.regex.Matcher class represents an engine for performing various matching operations. This class has no constructor and can be usedmatches()is created by the method of the class java.util.regex.Pattern/to obtain an object of this class.

The Matcher classusePattern()The method accepts a Pattern object representing the new regular expression pattern and uses it to find matches.

Example

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UsePatternExample {}}
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "[#%&*]";
      //Create a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Create a Matcher object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      //search pattern used
      System.out.println("The are "+count+" special characters [# % & *] in the given text");
      //to create an accepting5 t 6character pattern
      Pattern newPattern = Pattern.compile("\\A(?=\\w{6,15}\\z)");
      //Switch to new mode
      matcher = matcher.usePattern(newPattern);
      if(matcher.find()) {
         System.out.println("Given input contain 6 to 15 characters});
      } else {
         System.out.println("Given input doesn't contain 6 to 15 characters});
      }
   }
}

Output Result

Enter input text:
#*mypassword&
The are 3 special characters [# % & *] in the given text
!!mypassword!
Given input doesn't contain 6 to 15 characters