Use find() to find multiple subsequences in Java


The find() method finds the multiple subsequences in an input sequence that matches the pattern required. This method is available in the Matcher class that is available in the java.util.regex package

A program that uses the find() method to find multiple subsequence in Java 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("the");
      Matcher m = p.matcher("eclipses of the sun and the moon");
      System.out.println("Subsequence: the");
      System.out.println("Sequence: eclipses of the sun and the moon");
      System.out.println();
      while (m.find()) {
         System.out.println("the found at index " + m.start());
      }
   }
}

Output

Subsequence: the
Sequence: eclipses of the sun and the moon
the found at index 12
the found at index 24

Now let us understand the above program.

The subsequence “the” is searched in the string sequence "eclipses of the sun and the moon". Then the find() method is used to find if the subsequence is in the input sequence any number of times and the required result is printed. A code snippet which demonstrates this is as follows:

Pattern p = Pattern.compile("the");
Matcher m = p.matcher("eclipses of the sun and the moon");
System.out.println("Subsequence: the" );
System.out.println("Sequence: eclipses of the sun and the moon" );
System.out.println();
while (m.find()) {
   System.out.println("the found at index " + m.start());
}

Updated on: 30-Jul-2019

80 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements