Role of Matcher.find(int) method in Java Regular Expressions

Java 8Object Oriented ProgrammingProgramming

The Matcher.find(int) method finds the subsequence in an input sequence after the subsequence number that is specified as a parameter. This method is available in the Matcher class that is available in the java.util.regex package.

The Matcher.find(int) method has one parameter i.e. the subsequence number after which the subsequence is obtained and it returns true is the required subsequence is obtained else it returns false.

A program that demonstrates the method Matcher.find(int) in Java regular expressions is given as follows −

Example

 Live Demo

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
   public static void main(String args[]) {
      Pattern p = Pattern.compile("apple", Pattern.CASE_INSENSITIVE);
      Matcher m = p.matcher("apple APPLE Apple aPPLE");
      System.out.println("apple APPLE Apple aPPLE");
      m.find(6);
      System.out.println(m.group());
      System.out.println("\napple APPLE Apple aPPLE");
      m.find(12);
      System.out.println(m.group());
      System.out.println("\napple APPLE Apple aPPLE");
      m.find(0);
      System.out.println(m.group());
   }
}

The output of the above program is as follows −

apple APPLE Apple aPPLE
APPLE
apple APPLE Apple aPPLE
Apple
apple APPLE Apple aPPLE
apple

Now let us understand the above program.

The subsequence in the input sequence "apple APPLE Apple aPPLE" after the subsequence number 6, 12 and 0 is found using the find(int) method and the required result is printed. A code snippet which demonstrates this is as follows −

Pattern p = Pattern.compile("apple", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("apple APPLE Apple aPPLE");
System.out.println("apple APPLE Apple aPPLE");
m.find(6);
System.out.println(m.group());
System.out.println("\napple APPLE Apple aPPLE");
m.find(12);
System.out.println(m.group());
System.out.println("\napple APPLE Apple aPPLE");
m.find(0);
System.out.println(m.group());
raja
Published on 07-Feb-2019 13:16:44
Advertisements