CodexBloom - Programming Q&A Platform

Regex scenarios to Match Version Strings with Optional Build Metadata in Go

👀 Views: 56 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
regex go validation Go

Can someone help me understand I tried several approaches but none seem to work. I'm trying to validate semantic version strings in Go that may also include optional build metadata. The format I'm targeting is `MAJOR.MINOR.PATCH[-PRERELEASE][+BUILD]`, where `[-PRERELEASE]` is optional and can contain letters and numbers, and `[+BUILD]` is also optional but can only consist of alphanumeric characters and dots. I've crafted this regex pattern: ```go regex := `^(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z0-9\.]+))?(?:\+([a-zA-Z0-9\.]+))?$` ``` However, I'm finding that it's not matching certain version strings correctly. For example, `1.0.0-alpha+001` matches, but `1.0.0-alpha.1+build.123` does not, and I don't understand why. When I test it, I get this output: ``` expected match for '1.0.0-alpha.1+build.123', got no match ``` I've used Go's `regexp` package like this: ```go package main import ( "fmt" "regexp" ) func main() { version := "1.0.0-alpha.1+build.123" regex := `^(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z0-9\.]+))?(?:\+([a-zA-Z0-9\.]+))?$` re := regexp.MustCompile(regex) if re.MatchString(version) { fmt.Println("Matched!") } else { fmt.Println("No match!") } } ``` Is there something wrong with my regex, or is there an scenario with how I'm using it? Any insights or corrections would be greatly appreciated! Any ideas what could be causing this? I'd be grateful for any help. Is there a simpler solution I'm overlooking?