while i agree with the comment from user datenwolf here is another version which does not involve regular expressions.
It also handle more complex emails format including comma within the local parts. Something uneasy to implement using regexp.
see 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)
}
}