# 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 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.

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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’.
3. Match the given string with the regex, in Java this can be done by using Pattern.matcher().
4. 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 `

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.

My Personal Notes arrow_drop_up

External Technical Content Reviewer at GeeksforGeeks

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : AnkitRai01