- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
Quantifier | Description |
---|---|
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. |
Example
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()) { System.out.print(matcher.group()); System.out.println(); } } }
Output
Enter input text: 45678 45678
- Related Articles
- Reluctant quantifiers Java Regular expressions
- Regex quantifiers in Java Regular Expressions
- Explain quantifiers in Java regular expressions
- Greedy quantifiers Java Regular expressions in java.
- Java Regular Expressions Tutorial
- Explain C# Quantifiers in regular expression
- Java regular expressions sample examples
- Java Regular expressions Logical operators
- Back references in Java regular expressions
- Regular Expressions syntax in Java Regex
- Validate Phone with Java Regular Expressions
- Matcher.pattern() method in Java Regular Expressions
- Date validation using Java Regular Expressions
- Pattern.matches() method in Java Regular Expressions
- Name validation using Java Regular Expressions

Advertisements