从电子邮件地址中提取“域名”的方法

5
我在我的列中有以下模式。
xyz@gmail.com
abc@hotmail.com

现在,我想提取@.之间的文本,即电子邮件地址中的gmail和hotmail。我可以使用以下代码提取.后面的文本。
sub(".*@", "", email)

如何修改上述内容以适应我的使用情况?
4个回答

8

您需要阅读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()
  })
##                         host    subdomain      domain suffix
## 1                  gmail.com         <NA>       gmail    com
## 2                hotmail.com         <NA>     hotmail    com
## 3      deparment.example.com   department     example    com
## 4 yet.another.department.com  yet.another  department    com
## 5             froodyco.co.uk         <NA>   froodyorg  co.uk

请注意子域名、域名和后缀的正确分割,特别是最后一个。
了解这一点后,我们可以更改代码为:
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()
  })
## [1] "gmail"                   "hotmail"               
## [3] "department.example"      "yet.another.department"
## [5] "froodyorg"

5
我们可以使用 gsub
gsub(".*@|\\..*", "", email)
#[1] "gmail"   "hotmail"

3

您可以使用:

emails <- c("xyz@gmail.com", "abc@hotmail.com")
emails_new <- gsub("@(.+)$", "\\1", emails)
emails_new
# [1] "gmail.com"   "hotmail.com"

ideone.com上查看演示


看起来模式应该是 "@(.*)\\..*",你可以使用 sub - Wiktor Stribiżew

1

这是 @hrbrmstr 使用 stringr 的函数:

stringr::str_locate_all(email,"@") %>% purrr::map_int(~ .[2]) %>%
purrr::map2_df(email, ~ {
  stringr::str_sub(.y, .x+1, nchar(.y)) %>%
    urltools::suffix_extract()
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接