I'm having trouble pulling out the domain for emails. I've tried using variations of
u, _ := url.Parse(email)
and other parsing from the standard library, but nothing that seems to parse: [email protected] into separate parts.
I've also tried net.SplitHostPort with no luck.
I don't want to get create a function which gets the len and separate to get substring after @ symbol if possible.
Does anyone have any ideas to do this?
Thanks!
Here's an example I concocted from the golang documentation:
package main
import (
"fmt"
"strings"
)
func main() {
email := "[email protected]"
components := strings.Split(email, "@")
username, domain := components[0], components[1]
fmt.Printf("Username: %s, Domain: %s\n", username, domain)
}
UPDATE: 2020-09-01 - updating to use last @
sign per @Kevin's feedback in the comments.
package main
import (
"fmt"
"strings"
)
func main() {
email := "[email protected]"
at := strings.LastIndex(email, "@")
if at >= 0 {
username, domain := email[:at], email[at+1:]
fmt.Printf("Username: %s, Domain: %s\n", username, domain)
} else {
fmt.Printf("Error: %s is an invalid email address\n", email)
}
}
Here are some tests: https://play.golang.org/p/cg4RqZADLml
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With