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

How to use Java RegEx to match an expression n times?

Java's greedy quantifiers allow you to match expressions that appear multiple times. Where,

  • Exp {n} prompts the expression exp to appear exactly n times.

  • Exp {n,} prompts the expression exp to appear at least n times.

  • Exp {n, m} prompts the expression exp to appear at least n times and at most m times.

Example1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main(String args[]) {
      //regular expression accepts5letter words
      String regex = ";\\w{5");
      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();
      }
      //Create a Pattern object
      Pattern p = Pattern.compile(regex);
      for(int i=0; i<5;i++) {
         //Create a Matcher object
         Matcher m = p.matcher(input[i]);
         if(m.find()) {
            System.out.println(input[i]+: accepted");
         }
            System.out.println(input[i]+: not accepted");
         }
      }
   }
}

Output result

Enter 5 input strings:
rama
raja
raghu
megha
malya
rama: not accepted
raja: not accepted
raghu: accepted
megha: accepted
malya: accepted

Example2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main(String args[]) {
      //regular expression matching length of2to6non-word strings
      String regex = ";\\W{2,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();
      }
      //Create a Pattern object
      Pattern p = Pattern.compile(regex);
      for(int i=0; i<5;i++) {
         //Create a Matcher object
         Matcher m = p.matcher(input[i]);
         if(m.find()) {
            System.out.println(input[i]+" matched");
         }
      }
   }
}

Output1

Enter 5 input strings:
hello how are you
#$#%
#
#$@%%#&#&
sample text
#$#% matched
#$@%%#&#& matched

Example3

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 = "[a-zA-Z]{1,2"0"
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter student name:");
      String name = sc.nextLine();
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(name);
      if(m.matches()) {
         System.out.println("Name is appropriate");
      }
         System.out.println("Name is inappropriate");
      }
   }
}

Output result

Enter student name:
Mouktika
Name is appropriate