Semantic Version (SemVer) in GO
Match semantic version strings like 1.2.3, 1.2.3-beta.1, or 1.2.3+build.42.
Try it in the GO tester →Pattern
regexGO
(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[\w.]+)?(?:\+[\w.]+)? (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[\w.]+)?(?:\+[\w.]+)?`)
input := `1.0.0`
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
Three numeric components (no leading zeros) separated by dots. Optional pre-release label after - and optional build metadata after + per the SemVer 2.0.0 spec.
Examples
Input
1.0.0Matches
1.0.0
Input
2.3.1-beta.1Matches
2.3.1-beta.1
Input
1.0.0+build.42Matches
1.0.0+build.42