Home > Software engineering >  finding, parsing and validating email addresses
finding, parsing and validating email addresses

Time:11-02

 import "fmt"

func main() {
    email := "[email protected]"
    atTrue := false
    s := ""
    for i := 0; i < len(email); i   {
        if atTrue {
            s  = string(email[i])
        }
        if string(email[i]) == "@" {
            atTrue = true
        }
    }
    fmt.Println(s)
}

current output: gmail.com

expect output: Domain: gmail and TLD: com

How to indicate looping from certain string to certain string?

CodePudding user response:

Use strings.Split function

    email := "[email protected]"
    split := strings.Split(email, "@")
    split = strings.Split(split[1], ".")
    fmt.Println("Domain:", split[0])
    fmt.Println("TLD:", split[1])

optionally you can validate an email string with mail.ParseAddress function

    email := "[email protected]"
    addr, err := mail.ParseAddress(email)
    if err != nil {
        log.Fatal(err)
    }

what if the TLD goes like this co.id, does the output still co.id ? – @zacharyy

simply try to find the first index of . (strings.Index) and use one to separate the string

    email := "[email protected]"
    split := strings.Split(email, "@")
    index := strings.Index(split[1], ".")
    fmt.Println("Domain:", split[1][:index])
    fmt.Println("TLD:", split[1][index 1:])

or use regexp.Split function

    email := "[email protected]"
    split := strings.Split(email, "@")
    split = regexp.MustCompile("[.]").
        Split(split[1], 2)
    fmt.Println("Domain:", split[0])
    fmt.Println("TLD:", split[1])

or strings.SplitN

    email := "[email protected]"
    split := strings.Split(email, "@")
    split = strings.SplitN(split[1], ".", 2)
    fmt.Println("Domain:", split[0])
    fmt.Println("TLD:", split[1])

or strings.Cut

    _, host, found := strings.Cut(email, "@")
    if !found {
        t.Fatal("fail cut to host (Domain   TLD)")
    }
    domain, tld, found := strings.Cut(host, ".")
    if !found {
        t.Fatal("fail cut to Domain and TLD")
    }
    fmt.Println("Domain:", domain)
    fmt.Println("TLD:", tld)

  • Related