CodexBloom - Programming Q&A Platform

Struggling to Match Dates with Specific Formats in Golang Regex - advanced patterns with Group Captures

👀 Views: 190 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-19
regex golang validation Go

After trying multiple solutions online, I still can't figure this out. I'm relatively new to this, so bear with me. I'm having trouble using regex in Go to match dates in the format `YYYY-MM-DD` and `DD/MM/YYYY`. I want to validate these formats and extract the components as separate groups. However, I seem to be getting unexpected results when I run my regex. Here's the code I'm using: ```go package main import ( "fmt" "regexp" ) func main() { datePattern := `^(\d{4})-(\d{2})-(\d{2})$|^(\d{2})/(\d{2})/(\d{4})$` dates := []string{ "2023-10-04", "04/10/2023", "2023-10-32", // Invalid date "04/13/2023", // Invalid month } for _, date := range dates { re := regexp.MustCompile(datePattern) matches := re.FindStringSubmatch(date) if matches != nil { fmt.Println("Valid date found:", date) fmt.Println("Components:", matches) } else { fmt.Println("Invalid date:", date) } } } ``` I expected the output to indicate which dates are valid and print out the components, but for the invalid dates, I still seem to get some unexpected matches. Specifically, when I test `"2023-10-32"`, it returns a match where components for the year and month are correct, but the day is out of range. I also noticed that when I test `"04/13/2023"`, the regex doesn't throw an behavior but still captures the year and day incorrectly. Is there a way to ensure that only valid dates are captured, or do I need to modify my approach with additional validation besides just regex? I'm using Go version 1.19 and have read that regex can sometimes behave unexpectedly with certain patterns. Any advice or suggestions would be greatly appreciated! I'm coming from a different tech stack and learning Go. Hoping someone can shed some light on this. I'm working in a Ubuntu 20.04 environment. Thanks for your help in advance!