Java-Match Fixed length

Match Fixed length

It is also possible to designate a sequence of fixed length. For example, to specify four-digit numbers, we write [0-9]{4}. The number in the braces { and } denotes the number of repetitions. We can specify the minimum and maximum numbers of repetitions also. Here are the rules:

Expression Description
X{N} Repeat X exactly N times, where X is a regular
expression for a single character.
X{N,} Repeat X at least N times.
X{N,M} Repeat X at least N but no more than M times.

Program One

 

Program Two

 

Program Three


Program One Source

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Javaapp {
  
    public static void main(String[] args) {
        
        Pattern pat = Pattern.compile("[0-9]{3}");
        Matcher mat = pat.matcher("22 333 4444 55555 666666");
        
        int i = 0;
        while(mat.find())
        {
            i++;
            System.out.println(i+"th subsequence  : "+mat.group());
        }
    }
}

Program Two Source

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Javaapp {
  
    public static void main(String[] args) {
        
        Pattern pat = Pattern.compile("[0-9]{3,}");
        Matcher mat = pat.matcher("22 333 4444 55555 666666");
        
        int i = 0;
        while(mat.find())
        {
            i++;
            System.out.println(i+"th subsequence  : "+mat.group());
        }
    }
}

Program Three Source

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Javaapp {
  
    public static void main(String[] args) {
        
        Pattern pat = Pattern.compile("[0-9]{3,5}");
        Matcher mat = pat.matcher("22 333 4444 55555 666666");
        
        int i = 0;
        while(mat.find())
        {
            i++;
            System.out.println(i+"th subsequence  : "+mat.group());
        }
    }
}

Leave a Comment