
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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, } | Matches at least n occurrences. |
re{n, m} | Matches at least n and at most m occurrences. |
Example
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.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); System.out.println(“”Matched text: ); while (matcher.find()) { System.out.println(matcher.group()); } } }
Output
Enter input text: Matched text: 45545
- Related Questions & Answers
- Possessive quantifiers Java Regular expressions
- Reluctant quantifiers Java Regular expressions
- Regex quantifiers in Java Regular Expressions
- Explain quantifiers in Java regular expressions
- A greedy qualifier in Java Regular Expressions
- Java Regular Expressions Tutorial
- Java regular expressions sample examples
- Java Regular expressions Logical operators
- Quantifiers in Java
- Back references in Java regular expressions
- Regular Expressions syntax in Java Regex
- Matcher.pattern() method in Java Regular Expressions
- Pattern.matches() method in Java Regular Expressions
- PatternSyntaxException class in Java regular expressions
- Validate Phone with Java Regular Expressions
Advertisements