24-hour time regex (HH:MM)
Matches 24-hour clock times with optional seconds. Hours run 00 to 23, minutes and seconds 00 to 59, each captured in its own group.
The pattern
//g
Sample text, 2 matches
Standup at 09:30, deploy at 17:45:10, and 24:00 is not a valid time.
Point at a coloured group to see it in the pattern, the text and the explanation.
What it deliberately doesn’t do
- Leap seconds (23:59:60) and 24:00 are rejected.
- Single-digit hours (9:30) are not matched; make the first digit optional if you need them.
Explained, in order
\bWord boundary — asserts a boundary between a word character and a non-word character. Consumes no characters.([01]\d|2[0-3])Group 1.Capturing group #1 — groups the pattern and captures the matched text for later reference[01]\d|2[0-3]Alternation — matches any ONE of the 2 alternatives listed above/below[01]Character class — matches one character from: '0', '1'\dMatches a digit (0–9)2Matches the character '2' literally[0-3]Character class — matches one character from: '0' through '3':Matches the character ':' literally([0-5]\d)Group 2.Capturing group #2 — groups the pattern and captures the matched text for later reference[0-5]Character class — matches one character from: '0' through '5'\dMatches a digit (0–9)(?::([0-5]\d))Non-capturing group — groups the pattern without capturing:Matches the character ':' literally([0-5]\d)Group 3.Capturing group #3 — groups the pattern and captures the matched text for later reference[0-5]Character class — matches one character from: '0' through '5'\dMatches a digit (0–9)?The preceding element matches optionally (zero or one time) (greedy)\bWord boundary — asserts a boundary between a word character and a non-word character. Consumes no characters.
In your language
JavaScript
The engine this page was tested with.
const re = /\b([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?\b/g;
// Example
const matches = [...str.matchAll(/\b([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?\b/g)];
for (const m of matches) {
console.log(m[0], m.index, m.groups);
}Python
Translated. Named groups are rewritten to (?P<name>…).
import re
pattern = re.compile(r"\b([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?\b")
# Example
for m in pattern.finditer(text):
print(m.group(0), m.start(), m.groups())Go
Translated. Go's RE2 has no lookaround or backreferences.
package main
import (
"fmt"
"regexp"
)
var re = regexp.MustCompile(`\b([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?\b`)
func main() {
for _, match := range re.FindAllStringSubmatch(text, -1) {
fmt.Println(match[0], match)
}
}Rust
Translated. The regex crate has no lookaround or backreferences.
use regex::Regex;
// Note: Rust finds all matches via find_iter / captures_iter (no 'g' flag).
fn main() {
let re = Regex::new(r#"\b([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?\b"#).unwrap();
for m in re.find_iter(text) {
println!("{} at {}", m.as_str(), m.start());
}
}