Example 1: Implementation of Java Regular Expressions
KW.java
import java.util.*;
import java.util.regex.*;
class KW
{
    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
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW ____________________________________ Implementation of Regular Expression ____________________________________ Enter a number KW Error: number unacceptable ____________________________________ kodingwindow@kw:~$ java KW ____________________________________ Implementation of Regular Expression ____________________________________ Enter a number 12 Number accepted ____________________________________ kodingwindow@kw:~$
Example 2: Implementation of Java Regular Expressions
KW.java
import java.util.*;
import java.util.regex.*;
class KW
{
    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
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW ____________________________________ Implementation of Regular Expression ____________________________________ Enter your 6-digit PIN code -23566 Please enter digits only ____________________________________ kodingwindow@kw:~$ java KW ____________________________________ Implementation of Regular Expression ____________________________________ Enter your 6-digit PIN code 400099 Congratulations! your PIN code accepted successfully. ____________________________________ kodingwindow@kw:~$
Advertisement