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

Updated on: 19-Nov-2019

81 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements