12-Hour Time (H:MM AM/PM) Regex for Go
/^(1[0-2]|0?[1-9]):([0-5][0-9])(?::([0-5][0-9]))?\s?(AM|PM|am|pm|Am|Pm)$/iWhat this pattern does
This page provides a well-structured, multi-part regular expression for matching 12-hour time (h:mm am/pm), ported and verified for Go. A rigorously tested regex reduces debugging time and protects your application from edge-case failures. The snippet below is ready to drop into your Go project — whether you're validating in a Gin handler, a gRPC service, or a command-line tool.
Go Implementation
// 12-Hour Time (H:MM AM/PM)
// ReDoS-safe | RegexVault — Localization > Time Formats
package validation
import "regexp"
var 12hourTimeHmmAmpmRe = regexp.MustCompile(`^(1[0-2]|0?[1-9]):([0-5][0-9])(?::([0-5][0-9]))?\s?(AM|PM|am|pm|Am|Pm)$`)
func Validate12hourTimeHmmAmpm(s string) bool {
return 12hourTimeHmmAmpmRe.MatchString(s)
}
// Example
// fmt.Println(Validate12hourTimeHmmAmpm("12:30 PM")) // trueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
12:30 PM | 13:00 PM |
1:05 AM | 0:30 AM |
11:59:59 PM | 12:60 PM |
12:00 AM | 12:30 |
9:30am | 12:30 pm extra |
12:00PM | — |
When to use this pattern
This pattern is drawn from the Localization > Time Formats category and carries a ReDoS-safe certification. That matters for Go developers because Go's RE2 engine is inherently safe from catastrophic backtracking, but this pattern has been additionally verified for correctness. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
12:00 AM (midnight) and 12:00 PM (noon) confuse even native English speakers. Consider rejecting 12-hour format for any time-critical input and requiring 24-hour instead.
Technical Notes
12:00 AM = midnight, 12:00 PM = noon — the most commonly confused values. 12-hour format is standard in US, UK, Australia, and parts of Asia. Many others use 24-hour exclusively.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern