24-Hour Time in GO
Match 24-hour time formats HH:MM or HH:MM:SS with valid hour (00–23) and minute/second (00–59) ranges.
Try it in the GO tester →Pattern
regexGO
(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)? (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?`)
input := `14:30`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
How the pattern works
Hour alternation enforces 00–23, minute/second classes enforce 00–59. The optional :SS group makes seconds optional.
Examples
Input
14:30Matches
14:30
Input
23:59:59Matches
23:59:59
Input
25:00No match
—