If you want to specify the number of occurrences while constructing a regular expression you can use quantifiers. Following table lists out the quantifiers supported by Java regular expressions −
Quantifier | Description | Example |
---|---|---|
re* | zero or more occurrences. | [0-9]*: matches 0 or more digits. |
re? | One or, no occurrences at all. | [0-9]?: matches 0 or 1 digit. |
re+ | one or more occurrences. | [0-9]+: matches one or more digits. |
re{n} | n occurrences. | [0-9]{3}: matches 3 digits. |
re{n, } | at-least n occurrences. | [0-9]{3, }: matches at least 3 digits. |
re{n, m} | at-least n and at-most m occurrences. | [0-9]{2, 5}: matches if given input is a number with 3 to 5 digits. |
Example
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main( String args[] ) { String regex = "[0-9]{3,6}"; Scanner sc = new Scanner(System.in); System.out.println("Enter 5 input strings: "); String input[] = new String[5]; for (int i=0; i<5; i++) { input[i] = sc.nextLine(); } //Creating a Pattern object Pattern p = Pattern.compile(regex); System.out.println("Matched values: "); for(int i=0; i<5;i++) { //Creating a Matcher object Matcher m = p.matcher(input[i]); if(m.matches()) { System.out.println(m.group()+": accepted "); } } } }
Output
Enter 5 input strings: 12 154 4587 478365 4578952 Matched values: 154: accepted 4587: accepted 478365: accepted