Quantifiers in Java allow users to specify the number of occurrences to match against. These are used withregular 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 intothree types, that are Greedy, Reluctant, andPossessive.
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 Quantifiersimportjava.util.regex.Matcher;importjava.util.regex.Pattern;// Driver ClassclassGeeks{publicstaticvoidmain(String[]args){// Making an instance of Pattern class// By default quantifier "+" is GreedyPatternp=Pattern.compile("g+");// Making an instance of Matcher classMatcherm=p.matcher("ggg");while(m.find()){System.out.println("Pattern found from "+m.start()+" to "+(m.end()-1));}}}OutputPattern found from 0 to 2
Explanation:In the above example, the patterng+ means one or more occurrences ofg. Text isggg. The greedy matcher would match the longest text even if parts of the matching text also match. In this example,g andgg also match, but the greedy matcher producesggg.
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 Quantifiersimportjava.util.regex.Matcher;importjava.util.regex.Pattern;classGeeks{publicstaticvoidmain(String[]args){// Making an instance of Pattern class// Here "+" is a Reluctant quantifier because// a "?' is appended after it.Patternp=Pattern.compile("g+?");// Making an instance of Matcher classMatcherm=p.matcher("ggg");while(m.find()){System.out.println("Pattern found from "+m.start()+" to "+(m.end()-1));}}}OutputPattern found from 0 to 0Pattern found from 1 to 1Pattern 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 Quantifiersimportjava.util.regex.Matcher;importjava.util.regex.Pattern;classGeeks{publicstaticvoidmain(String[]args){// Making an instance of Pattern class// Here "+" is a Possessive quantifier because// a "+' is appended after it.Patternp=Pattern.compile("g++");// Making an instance of Matcher classMatcherm=p.matcher("ggg");while(m.find()){System.out.println("Pattern found from "+m.start()+" to "+(m.end()-1));}}}OutputPattern 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 Quantifiersimportjava.util.regex.Matcher;importjava.util.regex.Pattern;classGeeks{publicstaticvoidmain(String[]args){// Create a pattern with Greedy quantifierPatternpg=Pattern.compile("g+g");// Create same pattern with possessive quantifierPatternpp=Pattern.compile("g++g");System.out.println("Using Greedy Quantifier");Matchermg=pg.matcher("ggg");while(mg.find()){System.out.println("Pattern found from "+mg.start()+" to "+(mg.end()-1));}System.out.println("\nUsing Possessive Quantifier");Matchermp=pp.matcher("ggg");while(mp.find()){System.out.println("Pattern found from "+mp.start()+" to "+(mp.end()-1));}}}OutputUsing Greedy QuantifierPattern found from 0 to 2Using Possessive Quantifier
Explanation: In the above example, since the first quantifier is greedy,g+ matches the whole string. If we matchg+ with whole string,g+g doesn't match, the Greedy quantifier removes the last character, matchesgg withg+, and finds a match. In the Possessive quantifier, we start like Greedy.g+ matches the whole string, but matchingg+ with the whole string doesn't matchg+g withggg. Unlike Greedy, since quantifier is possessive, we stop at this point.
Explore
Java Basics
OOP & Interfaces
Collections
Exception Handling
Java Advanced
Practice Java