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:
- It should start from 1, 2, … 9 or 10, 11, 12.
- It should be followed by a colon(:).
- It should be followed by two digits between 00 to 59.
- It should only allow one white space, although this is optional.
- 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.
- Get the string.
- 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’.
- Match the given string with the regex, in Java this can be done by using Pattern.matcher().
- Return true if the string matches with the given regex, else return false.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <regex>
using namespace std;
bool isValidTime(string str)
{
const regex pattern(
"((([1-9])|(1[0-2])):([0-5])([0-9])(\\s)(A|P)M)" );
if (str.empty())
{
return false ;
}
if (regex_match(str, pattern))
{
return true ;
}
else
{
return false ;
}
}
int main()
{
string str1 = "12:15 AM" ;
cout << isValidTime(str1) << endl;
string str2 = "9:45 PM" ;
cout << isValidTime(str2) << endl;
string str3 = "1:15" ;
cout << isValidTime(str3) << endl;
string str4 = "17:30" ;
cout << isValidTime(str4) << endl;
return 0;
}
|
Java
import java.util.regex.*;
class GFG {
public static boolean isValidTime(String time)
{
String regexPattern
= "(1[012]|[1-9]):"
+ "[0-5][0-9](\\s)"
+ "?(?i)(am|pm)" ;
Pattern compiledPattern
= Pattern.compile(regexPattern);
if (time == null ) {
return false ;
}
Matcher m = compiledPattern.matcher(time);
return m.matches();
}
public static void main(String args[])
{
String str1 = "12:15 AM" ;
System.out.println(isValidTime(str1));
String str2 = "9:45PM" ;
System.out.println(isValidTime(str2));
String str3 = "1:15" ;
System.out.println(isValidTime(str3));
String str4 = "17:30" ;
System.out.println(isValidTime(str4));
}
}
|
Python3
import re
def isValidTime(time) :
regexPattern = "(1[012]|[1-9]):" + "[0-5][0-9](\\s)" + "?(?i)(am|pm)" ;
compiledPattern = re. compile (regexPattern);
if (time = = None ) :
return False ;
if re.search(compiledPattern,time):
return True
else :
return False
if __name__ = = "__main__" :
str1 = "12:15 AM" ;
print (isValidTime(str1));
str2 = "9:45PM" ;
print (isValidTime(str2));
str3 = "1:15" ;
print (isValidTime(str3));
str4 = "17:30" ;
print (isValidTime(str4));
|
C#
using System;
using System.Text.RegularExpressions;
class GFG
{
static void Main( string [] args)
{
string [] str={ "12:15 AM" , "9:45PM" , "1:15" , "17:30" };
foreach ( string s in str) {
Console.WriteLine( isValidTime(s) ? "true" : "false" );
}
Console.ReadKey(); }
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 );
}
}
|
Javascript
function isValidTime(str) {
let regex = new RegExp(/((1[0-2]|0?[1-9]):([0-5][0-9]) ?([AaPp][Mm]))/);
if (str == null ) {
return "false" ;
}
if (regex.test(str) == true ) {
return "true" ;
}
else {
return "false" ;
}
}
let str1 = "12:15 AM" ;
console.log(isValidTime(str1));
let str2 = "9:45PM" ;
console.log(isValidTime(str2));
let str3 = "1:15" ;
console.log(isValidTime(str3));
let str4 = "17:30" ;
console.log(isValidTime(str4));
|
Outputtrue
true
false
false
Time Complexity: O(N) for each testcase, where N is the length of the given string.
Auxiliary Space: O(1)