Friday 22 December 2017

How to write a regex to validate the 12-hour time format | Regex in java


Click here to watch on Youtube :
https://www.youtube.com/watch?v=_pcrNQvbEh0&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge

How to write a regex to validate the 12-hour time format | Regex in java
Time12HoursValidator.java

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

/**
 *
 * How to validate Time in 12 Hours format with regular expression
 *
 */

public class Time12HoursValidator
{

    private Pattern pattern;
    private Matcher matcher;

    private static final String TIME12HOURS_REGEX = "(1[012]|[1-9]):[0-5][0-9](\\s)?(?i)(am|pm)";

    public Time12HoursValidator()
    {
        pattern = Pattern.compile(TIME12HOURS_REGEX);
    }

    public boolean validate(final String time)
    {
        matcher = pattern.matcher(time);
        return matcher.matches();
    }
}

RegexDemo.java

import java.util.Arrays;
import java.util.List;

/**
 *
 * How to validate Time in 12 Hours format with regular expression
 *
 */

public class RegexDemo
{

    public static void main(String[] args)
    {
        List<String> validTimeList = Arrays.asList("2:00 am", "2:00 AM", "12:50 pm");

        Time12HoursValidator time12HoursValidator = new Time12HoursValidator();

       
        for (String time : validTimeList)
        {
            System.out.println(
                    time + " is Valid? = " + time12HoursValidator.validate(time));
        }
       
       

        System.out.println("--------------------------------------");
       
        List<String> inValidTimeList = Arrays.asList("0:00 am", "23:00 AM", "12:90 pm","11:20 GM");
       
        for (String time : inValidTimeList)
        {
            System.out.println(
                    time + " is Valid? = " + time12HoursValidator.validate(time));
        }


    }

}

Output

2:00 am is Valid? = true
2:00 AM is Valid? = true
12:50 pm is Valid? = true
--------------------------------------
0:00 am is Valid? = false
23:00 AM is Valid? = false
12:90 pm is Valid? = false
11:20 GM is Valid? = false

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

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/576579fab6c376d5ecd7cb5b7402b7fd1a7c4ae3/BasicJava/RegexDemo_time12hrs/?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
  • No comments:

    Post a Comment