The greedy quantifier is the default quantifier. If no match occurs, the greedy quantifier tries to match as much as possible from the input string (the longest match), and if a match fails it keeps the last character and tries again. The following is a list of greedy quantifiers:
Quantifier | Description |
---|---|
re* | Matches zero or more occurrences. |
re? | Matches zero or one occurrences. |
re | Matches one or more occurrences. |
re{n} | Exactly matches n occurrences. |
re{n, } | Match at least n occurrences. |
re{n, m} | Match at least n and at most m occurrences. |
In the following Java example, we are trying to match one or more numbers, our input string is 45545, although the values 4, 45, 455, etc. are all eligible, but because we use a greedy quantifier, it will match the longest possible value.
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()); } } }
Enter input text: Matched text: 45545
The above is the detailed content of Application of greedy quantifier in Java regular expressions. For more information, please follow other related articles on the PHP Chinese website!