URL Slug in GO
Validate URL slugs: lowercase letters and digits separated by single hyphens, no leading/trailing hyphens.
Try it in the GO tester →Pattern
regexGO
^[a-z0-9]+(?:-[a-z0-9]+)*$Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`)
input := `my-blog-post`
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
Anchored with ^ and $. Requires at least one alphanumeric character. Hyphens can only appear between alphanumeric groups — not at start or end.
Examples
Input
my-blog-postMatches
my-blog-post
Input
hello-world-123Matches
hello-world-123
Input
-bad-slug-No match
—