您需要阅读RFC 3696的第3节(简而言之:符号“@”可以出现在多个位置)。
看起来您没有考虑到电子邮件地址可能是“someone@department.example.com
”,“someone.else@yet.another.department.example.com
”(即天真地假设只有一个域名可能会在某些情况下对您进行分析),请注意。
如果您真的在寻找“电子邮件域名”,则还必须考虑什么构成了域名和合适的后缀,这一点您应该知道。
因此,除非您确信您拥有并将始终拥有简单的电子邮件地址,否则我建议:
library(stringi)
library(urltools)
library(dplyr)
library(purrr)
emails <- c("yz@gmail.com", "abc@hotmail.com",
"someone@department.example.com",
"someone.else@yet.another.department.com",
"some.brit@froodyorg.co.uk")
stri_locate_last_fixed(emails, "@")[,"end"] %>%
map2_df(emails, function(x, y) {
substr(y, x+1, nchar(y)) %>%
suffix_extract()
})
请注意子域名、域名和后缀的正确分割,特别是最后一个。
了解这一点后,我们可以更改代码为:
stri_locate_last_fixed(emails, "@")[,"end"] %>%
map2_chr(emails, function(x, y) {
substr(y, x+1, nchar(y)) %>%
suffix_extract() %>%
mutate(full_domain=ifelse(is.na(subdomain), domain, sprintf("%s.%s", subdomain, domain))) %>%
select(full_domain) %>%
flatten_chr()
})
"@(.*)\\..*"
,你可以使用sub
。 - Wiktor Stribiżew