Greedy quantifiers Java Regular expressions in java.

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. Following is the list of greedy 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, }Matches at least n occurrences.
re{n, m}Matches at least n and at most m occurrences.


In the following Java example we are trying to match 1 or more digits, our input string is 45545 though the values 4, 45, 455 etc… are eligible, since we are using greedy quantifier it matches the longest possible.

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.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);
      System.out.println(“”Matched text: );
      while (matcher.find()) {


Enter input text:
Matched text:

Updated on: 10-Jan-2020


Kickstart Your Career

Get certified by completing the course

Get Started