If you want to specify the number of occurrences while constructing a regular expression you can use quantifiers. Java supports three types of quantifiers namely: greedy quantifiers, reluctant quantifiers and possessive quantifiers.
Greedy quantifiers − 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.
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); System.out.println(""Matched text: ); while (matcher.find()) { System.out.println(matcher.group()); } } }
Output
Enter input text: Matched text: 45545
Reluctant quantifiers − a non-greedy/reluctant quantifier matches as little as possible, initially the non-greedy quantifier matches the first character if match not occurred it adds another character from the input string and tries to match. If you place a “?” after a greedy quantifier it becomes reluctant or non-greedy quantifier.
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.println(matcher.group()); } } }
Output
Enter input text: 12345678 1 2 3 4 5 6 7 8
Possessive quantifiers − 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:
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