Open In App

Validating traditional time formats using Regular Expression

Last Updated : 22 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string Time Format, the task is to check whether the string follows the time formats “HH: MM: SS” or “HH: MM” using Regular Expression. Rules for valid time formats:

  • It should contain only digits[0-9] and colon (:).
  • No alphabets are allowed or any special characters. 

Examples:

Input: “12: 55”
Output: True

Input: “24: 12: 12”
Output: False
Explanation: The standard time is never expressed 24:00:00 hours or anything else after that.

Approach: The problem can be solved based on the following idea:

Create a regex pattern to validate the number as written below:   
regex= ^(?:[01]?[0-9]|2[0-3]):[0-5]?[0-9](?::[0-5]?[0-9])?$

^ : Beginning of the string
?: : not compulsion to be present
[01] : indicates either 1 or 0
[0 – 9] : any one digit from 0 to 9 should be present.
\ : either first part before ” or second part after ”. 

Follow the below steps to implement the idea:

  • Create regex expression for Time formats.
  • Use Pattern class to compile the regex formed.
  •  Use the matcher function to check whether the Time format is valid or not.
  • If it is valid, return true. Otherwise, return false.

Below is the implementation of the above approach.

C++




// C++ program to validate the
// Traditional Time Formats (HH:MM:SS  or HH:MM)
// using RegularExpression
 
#include <bits/stdc++.h>
#include <regex>
using namespace std;
 
// Function to validate the
// Traditional Time Formats (HH:MM:SS  or HH:MM)
string isValidTime(string str)
{
    // Regex to check valid
    // Traditional Time Formats
    // (HH:MM:SS  or HH:MM).
    const regex pattern("^(?:[01]?[0-9]|2[0-3]):[0-5]?[0-9]"
                        "(?::[0-5]?[0-9])?$");
 
    // If the str
    // is empty return false
    if (str.empty()) {
        return "false";
    }
 
    // Return true if the str
    // matched the ReGex
    if (regex_match(str, pattern)) {
        return "true";
    }
    else {
        return "false";
    }
}
 
// Driver Code
int main()
{
    // Test Case 1:
    string str1 = "23:01:00";
    cout << isValidTime(str1) << endl;
 
    // Test Case 2:
    string str2 = "12:59:00";
    cout << isValidTime(str2) << endl;
 
    // Test Case 3:
    string str3 = "19:00:59";
    cout << isValidTime(str3) << endl;
 
    // Test Case 4:
    string str4 = "19:00:96";
    cout << isValidTime(str4) << endl;
 
    // Test Case 5:
    string str5 = "08:78:70";
    cout << isValidTime(str5) << endl;
 
    // Test Case 6:
    string str6 = "00:98:00";
    cout << isValidTime(str6) << endl;
 
    return 0;
}


Java




// Java code to implement the approach
 
import java.util.regex.*;
 
class GFG {
 
    // Function to validate the
    // Traditional Time Formats
    // (HH:MM:SS  or HH:MM)
    public static boolean isValidTime(String str)
    {
        // Regex to check valid Time
        String regex
            = "^(?:[01]?[0-9]|2[0-3]):[0-5]?[0-9](?::[0-5]?[0-9])?$";
 
        // Compile the ReGex
        Pattern p = Pattern.compile(regex);
 
        // If the str
        // is empty return false
        if (str == null) {
            return false;
        }
 
        // Pattern class contains matcher()
        // method to find matching between
        // given str using regex.
        Matcher m = p.matcher(str);
 
        // Return if the str
        // matched the ReGex
        return m.matches();
    }
 
    // Driver Code.
    public static void main(String args[])
    {
        // Test Case 1:
        String str1 = "23:10:59";
        System.out.println(isValidTime(str1));
 
        // Test Case 2:
        String str2 = "12:59:00";
        System.out.println(isValidTime(str2));
 
        // Test Case 3:
        String str3 = "19:00:59";
        System.out.println(isValidTime(str3));
 
        // Test Case 4:
        String str4 = "19:00:96";
        System.out.println(isValidTime(str4));
 
        // Test Case 5:
        String str5 = "08:78:70";
        System.out.println(isValidTime(str5));
 
        // Test Case 6:
        String str6 = "00:98:00";
        System.out.println(isValidTime(str6));
    }
}


Python3




# Python3 program to validate
# Traditional Time Formats (HH:MM:SS  or HH:MM)
# using Regular Expression
 
import re
 
 
# Function to validate
# Traditional Time Formats (HH:MM:SS  or HH:MM)
def isValidTime(str):
 
    # Regex to check valid time
    regex = "^(?:[01]?[0-9]|2[0-3]):[0-5]?[0-9](?::[0-5]?[0-9])?$"
 
    # Compile the ReGex
    p = re.compile(regex)
 
    # If the string is empty
    # return false
    if (str == None):
        return "false"
 
    # Return if the string
    # matched the ReGex
    if(re.search(p, str)):
        return "true"
    else:
        return "false"
 
 
# Driver code
if __name__ == '__main__':
     
    # Test Case 1:
    str1 = "23:01:00"
    print(isValidTime(str1))
     
    # Test Case 2:
    str2 = "12:59:00"
    print(isValidTime(str2))
     
    # Test Case 3:
    str3 = "19:00:59"
    print(isValidTime(str3))
     
    # Test Case 4:
    str4 = "19:00:96"
    print(isValidTime(str4))
     
    # Test Case 5:
    str5 = "08:78:70"
    print(isValidTime(str5))
     
    # Test Case 6:
    str6 = "00:98:00"
    print(isValidTime(str6))


C#




// Include namespace system
using System;
using System.Text.RegularExpressions;
 
public class GFG
{
 
  // Function to validate the
  // Traditional Time Formats
  // (HH:MM:SS  or HH:MM)
  public static bool isValidTime(String str)
  {
 
    // Regex to check valid LEI Code
    var regex = new Regex("^(?:[01]?[0-9]|2[0-3]):[0-5]?[0-9](?::[0-5]?[0-9])?$");
 
    // If the str
    // is empty return false
    if (str == null)
    {
      return false;
    }
 
    // Pattern class contains matcher()
    // method to find matching between
    // given LEI Code using regex.
    var m = regex.Match(str);
 
    // Return if the MICR Code
    // matched the ReGex
    return m.Success;
  }
 
  // Driver Code.
  public static void Main(String[] args)
  {
 
    // Test Case 1:
    var str1 = "23:10:59";
    Console.WriteLine(GFG.isValidTime(str1));
 
    // Test Case 2:
    var str2 = "12:59:00";
    Console.WriteLine(GFG.isValidTime(str2));
 
    // Test Case 3:
    var str3 = "19:00:59";
    Console.WriteLine(GFG.isValidTime(str3));
 
    // Test Case 4:
    var str4 = "19:00:96";
    Console.WriteLine(GFG.isValidTime(str4));
 
    // Test Case 5:
    var str5 = "08:78:70";
    Console.WriteLine(GFG.isValidTime(str5));
 
    // Test Case 6:
    var str6 = "00:98:00";
    Console.WriteLine(GFG.isValidTime(str6));
  }
}
 
// This code is contributed by Potta Lokesh.


Javascript




// Javascript program to validate
// Traditional Time Formats (HH:MM:SS  or HH:MM)
//using Regular Expression
 
// Function to validate the
// Traditional Time Formats (HH:MM:SS  or HH:MM)
function isValidTime(str) {
    // Regex to check valid
    // Traditional Time Formats (HH:MM:SS  or HH:MM)
    let regex = new RegExp(/^(?:[01]?[0-9]|2[0-3]):[0-5]?[0-9](?::[0-5]?[0-9])?$/);
 
    // 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 = "23:01:00";
console.log(isValidTime(str1));
 
// Test Case 2:
let str2 = "12:59:00";
console.log(isValidTime(str2));
 
// Test Case 3:
let str3 = "19:00:59";
console.log(isValidTime(str3));
 
// Test Case 4:
let str4 = "19:00:96";
console.log(isValidTime(str4));
 
// Test Case 5:
let str5 = "08:78:70";
console.log(isValidTime(str5));
 
// Test Case 6:
let str6 = "00:98:00";
console.log(isValidTime(str6));


Output

true
true
true
false
false
false

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

Related Articles:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads