登录
首页 >  Golang >  Go问答

如何在 Golang 中解析长字符串中的电子邮件地址

来源:stackoverflow

时间:2024-02-13 13:27:23 271浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《如何在 Golang 中解析长字符串中的电子邮件地址》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

如何从 golang 中的长字符串中仅提取电子邮件地址?例如:

"a bunch of irrelevant text fjewiwofjfjvnvkdlslsosiejwoqlwpwpwo
 [email protected],ou=f,c=US
 [email protected],ou=f,c=US
 [email protected],ou=f,c=US
 [email protected],ou=f,c=US
 [email protected],ou=people,ou=f,c=US
 [email protected],ou=f,c=US"

这将返回所有电子邮件的列表: [[电子邮件受保护]、[电子邮件受保护] 等...]

每个电子邮件地址都以“mail=”开头,以逗号“,”结尾。


正确答案


为此,您需要将长字符串分解为您需要的部分。您可以使用正则表达式进行过滤和搜索,以匹配您在上面看到的电子邮件模式。

这是一段使用正则表达式的代码,首先获取包含 "mail=" 的部分,然后进一步格式化电子邮件,删除结尾的 ,

import (
    "fmt"
    "regexp"
    "strings"
)

func main() {
    var re = regexp.MustCompile(`(?m)mail=[A-Za-z.@0-9]+\,`)
    var str = `a bunch of irrelevant text fjewiwofjfjvnvkdlslsosiejwoqlwpwpwo
 [email protected],ou=f,c=US
 [email protected],ou=f,c=US
 [email protected],ou=f,c=US
 [email protected],ou=f,c=US
 [email protected],ou=people,ou=f,c=US
 [email protected],ou=f,c=US`

    for i, match := range re.FindAllString(str, -1) {
        fmt.Println(match, "found at index", i)
        email := strings.Split(match, "=")[1]

        email = strings.ReplaceAll(email, ",", "")

        fmt.Print(email)
    }
}

今天关于《如何在 Golang 中解析长字符串中的电子邮件地址》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>