4 回答

TA贡献1853条经验 获得超6个赞
你可以使用 golang 的原始包是 regexp.Compile 或 regexp.MustCompile
r, _ := regexp.Compile(regexEmail)
newVariable := `a bunch of irrelevant text fjewiwofjfjvnvkdlslsosiejwoqlwpwpwo
mail=jim.halpert@gmail.com,ou=f,c=US
mail=apple.pie@gmail.com,ou=f,c=US
mail=hello.world@gmail.com,ou=f,c=US
mail=alex.alex@gmail.com,ou=f,c=US
mail=bob.jim@gmail.com,ou=people,ou=f,c=US
mail=arnold.schwarzenegger@gmail.com,ou=f,c=US`
fmt.Printf("%#v\n", r.FindStringSubmatch(newVariable))
fmt.Printf("%#v\n", r.SubexpNames())

TA贡献1906条经验 获得超10个赞
你可以使用这个包来做到这一点:
https://github.com/hamidteimouri/htutils/blob/main/htregex/htregex.go
// Emails finds all email strings
func Emails(text string) []string {
return match(text, EmailsRegex)
}

TA贡献1836条经验 获得超13个赞
为此,您需要将 long go string 分解为您需要的部分。您可以使用正则表达式进行过滤和搜索,以匹配您在上面看到的电子邮件模式。
这是一段使用正则表达式的代码,首先获取该部分,"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
mail=jim.halpert@gmail.com,ou=f,c=US
mail=apple.pie@gmail.com,ou=f,c=US
mail=hello.world@gmail.com,ou=f,c=US
mail=alex.alex@gmail.com,ou=f,c=US
mail=bob.jim@gmail.com,ou=people,ou=f,c=US
mail=arnold.schwarzenegger@gmail.com,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)
}
}

TA贡献1788条经验 获得超4个赞
虽然我同意用户 datenwolf 的评论,但这里是另一个不涉及正则表达式的版本。
它还处理更复杂的电子邮件格式,包括本地部分中的逗号。使用正则表达式不容易实现的东西。
请参阅https://stackoverflow.com/a/2049510/11892070
import (
"bufio"
"fmt"
"strings"
)
var str = `a bunch of irrelevant text fjewiwofjfjvnvkdlslsosiejwoqlwpwpwo
mail=jim.halpert@gmail.com,ou=f,c=US
mail=apple.pie@gmail.com,ou=f,c=US
mail=hello.world@gmail.com,ou=f,c=US
mail=alex.alex@gmail.com,ou=f,c=US
mail=bob.jim@gmail.com,ou=people,ou=f,c=US
mail=arnold.schwarzenegger@gmail.com,ou=f,c=US
mail=(comented)arnold.schwarzenegger@gmail.com,ou=f,c=US
mail="(with comma inside)arnold,schwarzenegger@gmail.com",ou=f,c=US
mail=nocommaatall@gmail.com`
func main() {
var emails []string
sc := bufio.NewScanner(strings.NewReader(str))
for sc.Scan() {
t := sc.Text()
if !strings.HasPrefix(t, "mail=") {
continue
}
t = t[5:]
// Lookup for the next comma after the @.
at := strings.Index(t, "@")
comma := strings.Index(t[at:], ",")
if comma < 0 {
email := strings.TrimSpace(t)
emails = append(emails, email)
continue
}
comma += at
email := strings.TrimSpace(t[:comma])
emails = append(emails, email)
}
for _, e := range emails {
fmt.Println(e)
}
}
- 4 回答
- 0 关注
- 224 浏览
添加回答
举报