Possessive quantifiers Java Regular expressions

Greedy quantifiers are the default quantifiers. A greedy quantifier matches as much as possible from the input string (longest match possible) if match not occurred it leaves the last character and matches again.

A possessive quantifier is similar to a greedy quantifier the only difference is it tries to match as many character as it can initially and, if match not occurred unlike greedy quantifier it does not backtrack.

If you place a "+" after a greedy quantifier it becomes possessive quantifier. Following is the list of possessive quantifiers −

re*+Matches zero or more occurrences.
re?+Matches zero or, 1 occurrence.
re++Matches one or more occurrences.
re{n}+Matches exactly n occurrences.
re{n, m}+Matches at least n and at most m occurrences.


 Live Demo

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "[0-9]++";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      while (matcher.find()) {


Enter input text:

Updated on: 10-Jan-2020


Kickstart Your Career

Get certified by completing the course

Get Started