Use the regexp package to compile patterns for email, URL, IP addresses, and phone numbers, then call MatchString to validate input. The following code defines common regex patterns and demonstrates how to test them against sample strings.
package main
import (
"fmt"
"regexp"
)
func main() {
// Email: Basic pattern for local@domain.tld
emailRe := regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
// URL: Basic pattern for http/https with domain
urlRe := regexp.MustCompile(`^https?://[a-zA-Z0-9.-]+(?:/[a-zA-Z0-9._~:/?#\[\]@!$&'()*+,;=-]*)?$`)
// IPv4: Dotted decimal notation
ipv4Re := regexp.MustCompile(`^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$`)
// Phone: US format (xxx) xxx-xxxx or xxx-xxx-xxxx
phoneRe := regexp.MustCompile(`^\(?([0-9]{3})\)?[-.\s]?([0-9]{3})[-.\s]?([0-9]{4})$`)
tests := map[string]func(string) bool{
"email": emailRe.MatchString,
"url": urlRe.MatchString,
"ipv4": ipv4Re.MatchString,
"phone": phoneRe.MatchString,
}
for name, fn := range tests {
fmt.Printf("%s: %v\n", name, fn("test@example.com")) // Replace with specific test cases per type
}
}