Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java Quantifiers
Next article icon

Java Quantifiers

Last Updated : 10 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Quantifiers in Java allow users to specify the number of occurrences to match against. These are used with regular expressions to specify the number of times a particular pattern or character can appear in the Input.

Below are some commonly used quantifiers in Java.

Quantifiers

Description

X*

Zero or more occurrences of X

X?

Zero or One occurrence of X

X+

One or More occurrences of X

X{n}

Exactly n occurrences of X

X{n, }

At least n occurrences of X

X{n, m}

Count of occurrences of X is from n to m

Types of Quantifiers in Java

The concept of quantifiers can be divided into three types, that are Greedy, Reluctant, and Possessive.

1. Greedy Quantifier (Default)

By default, quantifiers are Greedy. Greedy quantifiers try to match the longest text that matches a given pattern. Greedy quantifiers work by first reading the entire string before trying any match. If the whole text doesn't match, remove the last character and try again, repeating the process until a match is found.  

Example:

Java
// Java Program to demonstrate // Greedy Quantifiers import java.util.regex.Matcher; import java.util.regex.Pattern;   // Driver Class class Geeks {     public static void main(String[] args)     {         // Making an instance of Pattern class         // By default quantifier "+" is Greedy         Pattern p = Pattern.compile("g+");           // Making an instance of Matcher class         Matcher m = p.matcher("ggg");           while (m.find()){             System.out.println("Pattern found from " + m.start() +                                " to " + (m.end()-1));         }     } } 

Output
Pattern found from 0 to 2 

Explanation: In the above example, the pattern g+ means one or more occurrences of g. Text is ggg. The greedy matcher would match the longest text even if parts of the matching text also match. In this example, g and gg also match, but the greedy matcher produces ggg.

2. Reluctant Quantifier (Appending ? after a quantifier) 

This quantifier uses the approach that is the opposite of greedy quantifiers. It starts with the first character and processes one character at a time. 

Example:

Java
// Java Program to demonstrate // Reluctant Quantifiers import java.util.regex.Matcher; import java.util.regex.Pattern;  class Geeks {     public static void main(String[] args)     {         // Making an instance of Pattern class         // Here "+" is a Reluctant quantifier because         // a "?' is appended after it.         Pattern p = Pattern.compile("g+?");           // Making an instance of Matcher class         Matcher m = p.matcher("ggg");           while (m.find()){             System.out.println("Pattern found from " + m.start() +                                " to " + (m.end()-1));         }     } } 

Output
Pattern found from 0 to 0 Pattern found from 1 to 1 Pattern found from 2 to 2 

Explanation: In the above example, since the quantifier is reluctant, it matches the shortest part of the test with the pattern. It processes one character at a time.

3. Possessive Quantifier (Appending + after a quantifier) 

This quantifier matches as many characters as possible, like a greedy quantifier. But if the entire string doesn't match, then it doesn't try removing characters from the end.

Example:

Java
// Java program to demonstrate // Possessive Quantifiers import java.util.regex.Matcher; import java.util.regex.Pattern;   class Geeks {     public static void main(String[] args)     {         // Making an instance of Pattern class         // Here "+" is a Possessive quantifier because         // a "+' is appended after it.         Pattern p = Pattern.compile("g++");           // Making an instance of Matcher class         Matcher m = p.matcher("ggg");           while (m.find()){             System.out.println("Pattern found from " + m.start() +                                " to " + (m.end()-1));      	}     } } 

Output
Pattern found from 0 to 2 

Explanation: In the above example, we get the same output as Greedy because the whole text matches the pattern.

Greedy vs Possessive Quantifiers

There are some differences between Greedy and Possessive Quantifiers as mentioned below:

Aspect

Greedy Qualifiers

Possessive Quantifiers

Matching Behaviour

Matches as much as possible but allows backtracking if necessary

Matches as much as possible without backtracking

Backtracking

Allows backtracking

Doesn't need backtracking

Usage

Default quantifiers(* , + , {}) are greedy

Add a + after the quantifier( *+ , ++ , {n,m}+).

Performance

Can be slower due to backtracking

Can be faster, but may fail to match in some cases.

Example:

Java
// Java program to demonstrate difference  // between Possessive and Greedy Quantifiers import java.util.regex.Matcher; import java.util.regex.Pattern;   class Geeks {     public static void main(String[] args)     {         // Create a pattern with Greedy quantifier         Pattern pg = Pattern.compile("g+g");          // Create same pattern with possessive quantifier         Pattern pp = Pattern.compile("g++g");                   System.out.println("Using Greedy Quantifier");         Matcher mg = pg.matcher("ggg");                 while (mg.find()){             System.out.println("Pattern found from " + mg.start() +                                " to " + (mg.end()-1));          }                    System.out.println("\nUsing Possessive Quantifier");         Matcher mp = pp.matcher("ggg");                 	while (mp.find()){             System.out.println("Pattern found from " + mp.start() +                                " to " + (mp.end()-1));          }      } } 

Output
Using Greedy Quantifier Pattern found from 0 to 2  Using Possessive Quantifier 

Explanation: In the above example, since the first quantifier is greedy, g+ matches the whole string. If we match g+ with whole string, g+g doesn't match, the Greedy quantifier removes the last character, matches gg with g+, and finds a match. In the Possessive quantifier, we start like Greedy. g+ matches the whole string, but matching g+ with the whole string doesn't match g+g with ggg. Unlike Greedy, since quantifier is possessive, we stop at this point.


Next Article
Java Quantifiers

R

Rahul Agarwal
Improve
Article Tags :
  • Java
  • Technical Scripter
  • java-regular-expression
Practice Tags :
  • Java

Similar Reads

    Java Tutorial
    Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
    10 min read
    Java Pattern Class
    The Pattern class in Java is used for defining regular expressions (regex) to perform pattern matching on strings. It is part of the java.util.regex package and it plays a key role in searching, replacing, and manipulating strings based on patterns. The Matcher class works together with Pattern to p
    3 min read
    Java Syntax
    Java is an object-oriented programming language that is known for its simplicity, portability, and robustness. The syntax of Java programming language is very closely aligned with C and C++, which makes it easier to understand. Java Syntax refers to a set of rules that define how Java programs are w
    6 min read
    Java Identifiers
    An identifier in Java is the name given to Variables, Classes, Methods, Packages, Interfaces, etc. These are the unique names used to identify programming elements. Every Java Variable must be identified with a unique name.Example:public class Test{ public static void main(String[] args) { int a = 2
    2 min read
    Matcher Class in Java
    In Java, Matcher is a class that is implemented by the MatchResult interface, that performs match operations on a character sequence by interpreting a Pattern. Below, we can see the declaration of java.util.regex.Matcher in java.lang.Object Class: public final class Matcher extends Object implements
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences