Username in GO
Validate usernames that are 3–16 characters long and contain only letters, digits, underscores, and hyphens.
Try it in the GO tester →Pattern
regexGO
^[a-zA-Z0-9_\-]{3,16}$Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`^[a-zA-Z0-9_\-]{3,16}$`)
input := `john_doe`
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
^ and $ anchor to the full string. The character class [a-zA-Z0-9_\-] allows letters (upper and lower), digits, underscores, and hyphens. {3,16} enforces the length range most platforms use for usernames.
Examples
Input
john_doeMatches
john_doe
Input
user-123Matches
user-123
Input
abNo match
—