English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Regular Expression re {n} Meta Character in Java

Subexpression/The meta-character "re {n}" exactly matches the n-th occurrence of the preceding expression.

Example1

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 w3codebox";
      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 result

Number of matches: 2

Example2

Follow Java program to read age value from 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("Please 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()) {
         else {
      }
         System.out.println("Age value not accepted");
      }
   }
}

Output1

Please enter your age:
25
Age value accepted

Output2

Please enter your age:
2252
Age value not accepted

Output3

Please enter your age:
twenty
Age value not accepted