12-Hour Time with AM/PM in GO
Match 12-hour time formats with AM or PM suffix — e.g. 9:30 AM, 11:45:15 pm.
Try it in the GO tester →Pattern
regexGO
(?:0?[1-9]|1[0-2]):[0-5]\d(?::[0-5]\d)?\s?[AaPp][Mm] (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(?:0?[1-9]|1[0-2]):[0-5]\d(?::[0-5]\d)?\s?[AaPp][Mm]`)
input := `9:30 AM`
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 covers 1–12 (optional leading zero), minute/second classes enforce 00–59, optional whitespace separates the AM/PM suffix. Case-insensitive AM/PM via character classes.
Examples
Input
9:30 AMMatches
9:30 AM
Input
11:45:15 pmMatches
11:45:15 pm
Input
13:00 PMNo match
—