Example 1: Implementation of Java Regular Expressions
Codeaft.java
import java.util.*;
import java.util.regex.*;
class Codeaft
{
    public static void main(String args[])
    {
        String s;
        Scanner sc=new Scanner(System.in);
        System.out.println("____________________________________");
        System.out.println("Implementation of Regular Expression");
        System.out.println("____________________________________");
        System.out.print("Enter a number ");
        s=sc.nextLine();
        if(Pattern.matches("\\d*",s))
        {
            System.out.println("\nNumber accepted");
        }
        else
        {
            System.out.println("\nError: number unacceptable");
        }
        System.out.println("____________________________________");
    }       
}
Output
codeaft@codeaft:~$ javac Codeaft.java
codeaft@codeaft:~$ java Codeaft ____________________________________ Implementation of Regular Expression ____________________________________ Enter a number Codeaft Error: number unacceptable ____________________________________ codeaft@codeaft:~$ java Codeaft ____________________________________ Implementation of Regular Expression ____________________________________ Enter a number 12 Number accepted ____________________________________ codeaft@codeaft:~$
Example 2: Implementation of Java Regular Expressions
Codeaft.java
import java.util.*;
import java.util.regex.*;
class Codeaft
{
    public static void main(String args[])
    {
        String s;
        Scanner sc=new Scanner(System.in);
        System.out.println("____________________________________");
        System.out.println("Implementation of Regular Expression");
        System.out.println("____________________________________");
        System.out.print("Enter your 6-digit PIN code ");
        s=sc.nextLine();
        if(Pattern.matches("\\d{6}",s))
        {
            System.out.println("\nCongratulations! your PIN code accepted successfully.");
        }
        else
        {
            System.out.println("\nPlease enter digits only");
        }
        System.out.println("____________________________________");
    }       
}
Output
codeaft@codeaft:~$ javac Codeaft.java
codeaft@codeaft:~$ java Codeaft ____________________________________ Implementation of Regular Expression ____________________________________ Enter your 6-digit PIN code -23566 Please enter digits only ____________________________________ codeaft@codeaft:~$ java Codeaft ____________________________________ Implementation of Regular Expression ____________________________________ Enter your 6-digit PIN code 400099 Congratulations! your PIN code accepted successfully. ____________________________________ codeaft@codeaft:~$
Comments and Reactions