Example 1: Implementation of Java Regular Expressions
Codeaft.java
importjava.util.*;importjava.util.regex.*;classCodeaft{publicstaticvoidmain(Stringargs[]){Strings;Scannersc=newScanner(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
importjava.util.*;importjava.util.regex.*;classCodeaft{publicstaticvoidmain(Stringargs[]){Strings;Scannersc=newScanner(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:~$
Dear User, Thank you for visitng Codeaft. If you are interested in technical articles, latest technologies, and our journey further, please follow us on LinkedIn.