CodexBloom - Programming Q&A Platform

Regex scenarios to Extract Custom Log Timestamps in Go - Need guide with Different Formats

👀 Views: 41 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-24
regex go log-parsing Go

I'm working on a personal project and I'm trying to parse a custom log file in Go, which contains timestamps in various formats, including `2023-10-10 14:30:00`, `10/10/2023 2:30 PM`, and `October 10, 2023 14:30`. I need a regex pattern that can correctly identify and extract these timestamps. However, my current solution only captures the first format and fails for the others. Here's what I've attempted: ```go package main import ( "fmt" "regexp" ) func main() { logData := `2023-10-10 14:30:00 10/10/2023 2:30 PM October 10, 2023 14:30` // My current regex regex := `(?P<timestamp>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})` r := regexp.MustCompile(regex) matches := r.FindAllStringSubmatch(logData, -1) for _, match := range matches { fmt.Println(match) } } ``` This regex captures only the first timestamp format. When I try to add variations for the other formats, the pattern gets too complex and doesn't match anything at all. For example, adding `|(?P<timestamp>\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{2} (AM|PM))` results in an empty match output. I'm especially confused about how to handle the different separators and time formats. Any suggestions for a more robust regex pattern that can handle all three timestamp formats would be greatly appreciated! I'm using Go version 1.18. Is there a better approach? My development environment is Ubuntu. My development environment is Linux.