英文:
golang get domain from email using parse standard library
问题
我在提取电子邮件的域名方面遇到了问题。我尝试使用以下代码的变体:
u, _ := url.Parse(email)
以及其他标准库中的解析方法,但似乎没有将 user@gmail.com 解析成单独的部分。
我还尝试了 net.SplitHostPort,但没有成功。
如果可能的话,我不想创建一个函数来获取长度并分离出 @ 符号后的子字符串。
有人有什么想法吗?
谢谢!
英文:
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: user@gmail.com 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!
答案1
得分: 17
这是我从golang文档中编写的一个示例:
package main
import (
"fmt"
"strings"
)
func main() {
email := "foo@bar.com"
components := strings.Split(email, "@")
username, domain := components[0], components[1]
fmt.Printf("Username: %s, Domain: %s\n", username, domain)
}
更新:2020-09-01 - 根据@Kevin在评论中的反馈,更新为使用最后一个@
符号。
package main
import (
"fmt"
"strings"
)
func main() {
email := "foo@bar.com"
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)
}
}
这里是一些测试:https://play.golang.org/p/cg4RqZADLml
英文:
Here's an example I concocted from the golang documentation:
package main
import (
"fmt"
"strings"
)
func main() {
email := "foo@bar.com"
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 := "foo@bar.com"
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论