Pattern Breakdown
Understanding the regex pattern ^([01]?[0-9]|2[0-3]):[0-5][0-9]$:
- ^ - Start of string
- $ - End of string
- ? - Optional (zero or one)
- [...] - Character class
- (...) - Capturing group
- | - Alternation (OR)
Examples
| Input | Result | Explanation |
|---|---|---|
23:59 |
✓ Match | Last minute of day |
00:00 |
✓ Match | Midnight |
9:30 |
✓ Match | Single digit hour |
24:00 |
✗ No Match | Invalid hour |
Code Examples
JavaScript
JavaScript
const pattern = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
const text = "23:59";
// 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'^([01]?[0-9]|2[0-3]):[0-5][0-9]$'
text = "23:59"
# 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 = '/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/';
$text = "23:59";
// 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 = "^([01]?[0-9]|2[0-3]):[0-5][0-9]$";
String text = "23:59";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
if (m.matches()) {
System.out.println("Valid!");
}
Use Cases
Common applications: Scheduling systems, time pickers, international apps
- 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 24-hour time regex?
The regex pattern is: ^([01]?[0-9]|2[0-3]):[0-5][0-9]$. Match 24-hour time format HH:MM with proper hour (0-23) and minute (0-59) validation.
How do I use the 24-hour time regex pattern in JavaScript?
In JavaScript: const regex = new RegExp('^([01]?[0-9]|2[0-3]):[0-5][0-9]$'); or const regex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
Does this pattern work in Python?
Yes, use: import re; pattern = re.compile(r'^([01]?[0-9]|2[0-3]):[0-5][0-9]$') in Python. Most regex patterns are cross-language compatible.
What are common use cases for 24-hour time regex?
Scheduling systems, time pickers, international apps
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