How to Validate Input with Regex in Go

Validate input in Go by compiling a regex pattern with regexp.MustCompile and checking matches using MatchString.

Use the regexp package to compile a pattern and call MatchString to validate input. This returns a boolean indicating if the string matches the regex.

package main

import (
	"fmt"
	"regexp"
)

func main() {
	pattern := `^[a-zA-Z0-9_]+$`
	re := regexp.MustCompile(pattern)
	input := "valid_user_123"

	if re.MatchString(input) {
		fmt.Println("Valid")
	} else {
		fmt.Println("Invalid")
	}
}