Quantifiers in Java

Java 8Server Side ProgrammingProgramming

Quantifier is a concept that allows the programmer to specify the number of occurrences of a specific type of value in the regular expression. There are different types of quantifiers, some of them include ‘?’ (Reluctant quantifier), ‘+’ (Possessive quantifier). In this post, we will see how reluctant quantifier works.

Example

Following is an example −

 Live Demo

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
   public static void main(String[] args) {
      Pattern my_pattern = Pattern.compile("sam+?");
      Matcher my_match = my_pattern.matcher("samp");
      while (my_match.find())
      System.out.println("The pattern has been found - " + my_match.start() + " to " + (my_match.end()-1));
   }
}

Output

The pattern has been found - 0 to 2

A class named Demo contains the main function. A pattern class instance is created, and a Matcher class instance is created to check if a match is found for a specific pattern. The ‘find’ function is used to check if a match has been found, and if this is true, relevant message is printed on the screen.

raja
Published on 14-Sep-2020 12:49:31
Advertisements