Friday 22 December 2017

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


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

Click the below Image to Enlarge

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

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

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

public class Time24HoursValidator
{

    private Pattern pattern;
    private Matcher matcher;

    private static final String TIME24HOURS_REGEX = "([01]?[0-9]|2[0-3]):[0-5][0-9]";

    public Time24HoursValidator()
    {
        pattern = Pattern.compile(TIME24HOURS_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 24 Hours format with regular expression
 *
 */

public class RegexDemo
{

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

        Time24HoursValidator time24HoursValidator = new Time24HoursValidator();

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

        System.out.println("--------------------------------------");

        List<String> inValidTimeList = Arrays.asList("24:00", "13:1", "1:9", "110:20");

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


    }

}

Output

2:00 is Valid? = true
23:00 is Valid? = true
14:50 is Valid? = true
--------------------------------------
24:00 is Valid? = false
13:1 is Valid? = false
1:9 is Valid? = false
110:20 is Valid? = false

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

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

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