Email Address Validation in GO
Match and validate email addresses in the standard user@domain.tld format.
Try it in the GO tester →Pattern
regexGO
[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,} (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}`)
input := `user@example.com`
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
Matches a local part (letters, digits, dots, underscores, percent, plus, hyphen) followed by @, a domain name, a dot, and a TLD of at least 2 characters.
Examples
Input
user@example.comMatches
user@example.com
Input
hello.world+tag@sub.domain.orgMatches
hello.world+tag@sub.domain.org
Input
invalid-emailNo match
—