Thursday 30 November 2017

How to create a regex that accepts alphanumeric characters and length is 4 | Java Regex


Click here to watch in Youtube : 
https://www.youtube.com/watch?v=aGo-W_vIfx0&list=UUhwKlOVR041tngjerWxVccw

RegexDemo.java
import java.util.regex.Pattern;

/**
 *
 * Create a regular expression that accepts alpha numeric characters only. Its
 * length must be 4 characters long only.
 *
 */

public class RegexDemo
{
    public static void main(String[] args)
    {
        /*
         * Parameters:
         * 
         * regex - The expression to be compiled
         * 
         * input - The character sequence to be matched
         * 
         * Returns:
         * 
         * whether or not the regular expression matches on the input
         * 
         */
        System.out.println(Pattern.matches("[a-zA-Z0-9]{4}", "Juli"));//true
        System.out.println(Pattern.matches("[a-zA-Z0-9]{4}", "Ju22"));//true
        System.out.println(Pattern.matches("[a-zA-Z0-9]{4}", "Peter"));//false (more than 4 char)
        System.out.println(Pattern.matches("[a-zA-Z0-9]{4}", "J$22"));//false ($ is not matched)
    }

}
Output
true
true
false
false

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/RegexDemo_alphanumeric_length_4.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/RegexDemo_alphanumeric_length_4

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/950c9f162cb72194a90be45ab9293fca2b84f41c/BasicJava/RegexDemo_alphanumeric_length_4/?at=master

See also:

  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • 1 comment: