Quantifiers in Java


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.

Updated on: 14-Sep-2020

185 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements