Open In App

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

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 a 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)";

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’.
1. Match the given string with the regex, in Java this can be done by using Pattern.matcher().
2. Return true if the string matches with the given regex, else return false.

Below is the implementation of the above approach:

## C++

 // C++ program to validate// time in 12-hour format// using Regular Expression#include #include using namespace std; // Function to validate time in 12-hour formatbool 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 Codeint 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

## 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 the//  Time in 12-hour format//using Regular Expressionsusing System;using System.Text.RegularExpressions;class GFG{   // Main Method  static void Main(string[] args)  {     // Input strings to Match    // Time in 12-hour format    string[] str={"12:15 AM","9:45PM" ,"1:15","17:30"};    foreach(string s in str) {      Console.WriteLine( isValidTime(s) ? "true" : "false");    }    Console.ReadKey(); }   // method containing the regex  public static bool isValidTime(string str)  {    string strRegex = @"(1[012]|[1-9]):[0-5][0-9](\s)?(?i)(am|pm)";    Regex re = new Regex(strRegex);    if (re.IsMatch(str))      return (true);    else      return (false);  }} // This code is contributed by Rahul Chauhan

## Javascript

 // Javascript program to validate the time in// 12-hour format using Regular Expression. // Function to validate the// time in// 12-hour formatfunction isValidTime(str) {    // Regex to check valid    // time in 12-hour format    let regex = new RegExp(/((1[0-2]|0?[1-9]):([0-5][0-9]) ?([AaPp][Mm]))/);     //  if str    // is empty return false    if (str == null) {        return "false";    }     // Return true if the str    // matched the ReGex    if (regex.test(str) == true) {        return "true";    }    else {        return "false";    }} // Driver Code// Test Case 1:let str1 = "12:15 AM";console.log(isValidTime(str1)); // Test Case 2:let str2 = "9:45PM";console.log(isValidTime(str2)); // Test Case 3:let str3 = "1:15";console.log(isValidTime(str3)); // Test Case 4:let str4 = "17:30";console.log(isValidTime(str4)); // This code is contributed by Rahul Chauhan

Output

true
true
false
false

Time Complexity: O(N) for each testcase, where N is the length of the given string.
Auxiliary Space: O(1)