Skip to content
Related Articles

Related Articles

Improve Article

How to validate time in 12-hour format using Regular Expression

  • Difficulty Level : Easy
  • Last Updated : 27 Jan, 2021

Given a string str, the task is to check whether the string is valid time in 12-hour format or not by using Regular Expression
The valid time in 12-hour format must satisfy the following conditions:

  1. It should start from 1, 2, … 9 or 10, 11, 12.
  2. It should be followed by a colon(:).
  3. It should be followed by two digits between 00 to 59.
  4. It should only allow one white space, although this is optional.
  5. It should end with ‘am’, ‘pm’ or ‘AM’, ‘PM’.

Examples:  

Input: str = 12:15 AM 
Output: true 
Explanation: The given string satisfies all the above mentioned conditions.

Input: str = 9:45PM 
Output: true 
Explanation: The given string satisfies all the above mentioned conditions.

Input: str = 1:15 
Output: false 
Explanation: The given string does not end with ‘AM’ or ‘PM’, therefore it is not a valid time in 12-hour format.



Input: str = 17:30 PM 
Output: false 
Explanation: The given string does not have hours in between 1 to 12, therefore it is not a valid time in 12-hour format. 

Approach: This problem can be solved by using Regular Expression. 

  1. Get the string.
  2. Create a regular expression to check time in 12-hour format as mentioned below:
regex = "(1[012]|[1-9]):[0-5][0-9](\\s)?(?i)(am|pm)";
  1. Where: 
    • ( represents the start of the group.
    • 1[012]|[1-9] represents time start with 10, 11, 12 or 1, 2, …. 9
    • ) represents the end of the group.
    • : represents time must be followed by colon(:).
    • [0-5][0-9] represents the time followed by 00 to 59.
    • (\\s)? represents white space, time followed by a white space which is optional.
    • (?i) represents case insensitive, ‘am’, ‘pm’ or ‘AM’, ‘PM’ are same respectively.
    • (am|pm) represents time should end with ‘am’, ‘pm’ or ‘AM’, ‘PM’.
  2. Match the given string with the regex, in Java this can be done by using Pattern.matcher().
  3. Return true if the string matches with the given regex, else return false.

Below is the implementation of the above approach: 

Java




// Java program to validate the time in
// 12-hour format using Regular Expression.
 
import java.util.regex.*;
 
class GFG {
 
    // Function to validate the time in 12-hour format.
    public static boolean isValidTime(String time)
    {
 
        // Regex to check valid time in 12-hour format.
        String regexPattern
            = "(1[012]|[1-9]):"
              + "[0-5][0-9](\\s)"
              + "?(?i)(am|pm)";
 
        // Compile the ReGex
        Pattern compiledPattern
            = Pattern.compile(regexPattern);
 
        // If the time is empty
        // return false
        if (time == null) {
            return false;
        }
 
        // Pattern class contains matcher() method
        // to find matching between given time
        // and regular expression.
        Matcher m = compiledPattern.matcher(time);
 
        // Return if the time
        // matched the ReGex
        return m.matches();
    }
 
    // Driver Code.
    public static void main(String args[])
    {
 
        // Test Case 1:
        String str1 = "12:15 AM";
        System.out.println(isValidTime(str1));
 
        // Test Case 2:
        String str2 = "9:45PM";
        System.out.println(isValidTime(str2));
 
        // Test Case 3:
        String str3 = "1:15";
        System.out.println(isValidTime(str3));
 
        // Test Case 4:
        String str4 = "17:30";
        System.out.println(isValidTime(str4));
    }
}

Python3




# Python3 program to validate the time in
# 12-hour format using Regular Expression.
import re
 
# Function to validate the time in 12-hour format.
def isValidTime(time) :
     
    # Regex to check valid time in 12-hour format.
    regexPattern = "(1[012]|[1-9]):"+ "[0-5][0-9](\\s)"+ "?(?i)(am|pm)";
 
    # Compile the ReGex
    compiledPattern = re.compile(regexPattern);
 
    # If the time is empty
    # return false
    if (time == None) :
        return False;
     
    # re library contains search() method
    # to find matching between given time
    # and regular expression.
    # Return if the time
    # matched the ReGex
    if re.search(compiledPattern,time):
        return True
    else :
        return False
 
# Driver Code.
if __name__ == "__main__" :
 
    # Test Case 1:
    str1 = "12:15 AM";
    print(isValidTime(str1));
 
    # Test Case 2:
    str2 = "9:45PM";
    print(isValidTime(str2));
 
    # Test Case 3:
    str3 = "1:15";
    print(isValidTime(str3));
 
    # Test Case 4:
    str4 = "17:30";
    print(isValidTime(str4));
 
# This code is contributed by AnkitRai01

C++




// C++ program to validate
// time in 12-hour format
// using Regular Expression
#include <iostream>
#include <regex>
using namespace std;
 
// Function to validate time in 12-hour format
bool isValidTime(string str)
{
 
    // Regex to check valid time in 12-hour format
    const regex pattern(
        "((([1-9])|(1[0-2])):([0-5])([0-9])(\\s)(A|P)M)");
 
    // If the time in 12-hour format
    // is empty return false
    if (str.empty())
    {
        return false;
    }
 
    // Return true if the time in 12-hour format
    // matched the ReGex
    if (regex_match(str, pattern))
    {
        return true;
    }
    else
    {
        return false;
    }
}
 
// Driver Code
int main()
{
    // Test Case 1:
    string str1 = "12:15 AM";
    cout << isValidTime(str1) << endl;
 
    // Test Case 2:
    string str2 = "9:45 PM";
    cout << isValidTime(str2) << endl;
 
    // Test Case 3:
    string str3 = "1:15";
    cout << isValidTime(str3) << endl;
 
    // Test Case 4:
    string str4 = "17:30";
    cout << isValidTime(str4) << endl;
 
    return 0;
}
 
// This code is contributed by yuvraj_chandra
Output
true
true
false
false

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :