Pattern Breakdown
Understanding the regex pattern ^(0?[1-9]|1[0-2]):[0-5][0-9]\s?(AM|PM|am|pm)$:
- ^ - Start of string
- $ - End of string
- \s - Whitespace character
- ? - Optional (zero or one)
- [...] - Character class
- (...) - Capturing group
- | - Alternation (OR)
Examples
| Input | Result | Explanation |
|---|---|---|
12:30 PM |
✓ Match | Afternoon time |
9:15 AM |
✓ Match | Morning time |
00:30 AM |
✗ No Match | Invalid 12-hour format |
Code Examples
JavaScript
JavaScript
const pattern = /^(0?[1-9]|1[0-2]):[0-5][0-9]\s?(AM|PM|am|pm)$/;
const text = "12:30 PM";
// Test if string matches
if (pattern.test(text)) {
console.log("Valid!");
}
// Extract matches
const matches = text.match(pattern);
console.log(matches);
Python
Python
import re
pattern = r'^(0?[1-9]|1[0-2]):[0-5][0-9]\s?(AM|PM|am|pm)$'
text = "12:30 PM"
# Test if string matches
if re.match(pattern, text):
print("Valid!")
# Find all matches
matches = re.findall(pattern, text)
print(matches)
PHP
PHP
<?php
$pattern = '/^(0?[1-9]|1[0-2]):[0-5][0-9]\s?(AM|PM|am|pm)$/';
$text = "12:30 PM";
// Test if string matches
if (preg_match($pattern, $text)) {
echo "Valid!";
}
// Find all matches
preg_match_all($pattern, $text, $matches);
print_r($matches);
?>
Java
Java
import java.util.regex.*;
String pattern = "^(0?[1-9]|1[0-2]):[0-5][0-9]\\s?(AM|PM|am|pm)$";
String text = "12:30 PM";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
if (m.matches()) {
System.out.println("Valid!");
}
Use Cases
Common applications: US applications, user-friendly time input
- Form validation and input sanitization
- Data extraction and parsing
- Search and replace operations
- API request/response validation
- Log file analysis
Frequently Asked Questions
What is the regex pattern for 12-hour time regex?
The regex pattern is: ^(0?[1-9]|1[0-2]):[0-5][0-9]\s?(AM|PM|am|pm)$. Match 12-hour time format with AM/PM indicator. Allows optional leading zero.
How do I use the 12-hour time regex pattern in JavaScript?
In JavaScript: const regex = new RegExp('^(0?[1-9]|1[0-2]):[0-5][0-9]\\s?(AM|PM|am|pm)$'); or const regex = /^(0?[1-9]|1[0-2]):[0-5][0-9]\s?(AM|PM|am|pm)$/;
Does this pattern work in Python?
Yes, use: import re; pattern = re.compile(r'^(0?[1-9]|1[0-2]):[0-5][0-9]\s?(AM|PM|am|pm)$') in Python. Most regex patterns are cross-language compatible.
What are common use cases for 12-hour time regex?
US applications, user-friendly time input
Related Regex Patterns
More Regex Tools
GetDevUtils offers a suite of developer tools including:
- Regex Tester - Test and debug regular expressions
- JSON Formatter - Format and validate JSON
- Base64 Encoder/Decoder - Encode and decode Base64
- URL Encoder/Decoder - Encode and decode URLs