 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Regular Expression re{ n} Metacharacter in Java
The subexpression/metacharacter “re{ n}” matches exactly n number of occurrences of the preceding expression.
Example 1
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample {    public static void main( String args[] ) {       String regex = "to{1}";       String input = "Welcome to Tutorialspoint";       Pattern p = Pattern.compile(regex);       Matcher m = p.matcher(input);       int count = 0;       while(m.find()) {          count++;       }       System.out.println("Number of matches: "+count);    } }  Output
Number of matches: 2
Example 2
Following Java program reads age value from the user it only allows a two-digit number.
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample {    public static void main( String args[] ) {       String regex = "\d{2}";       System.out.println("Enter your age:");       Scanner sc = new Scanner(System.in);       String input = sc.nextLine();       Pattern p = Pattern.compile(regex);       Matcher m = p.matcher(input);       if(m.matches()) {          System.out.println("Age value accepted");       } else {          System.out.println("Age value not accepted");       }    } }  Output 1
Enter your age: 25 Age value accepted
Output 2
Enter your age: 2252 Age value not accepted
Output 3
Enter your age: twenty Age value not accepted
Advertisements
 