【问题标题】:Domain name regex域名正则表达式
【发布时间】:2024-08-30 10:50:02
【问题描述】:

试图从 URL 中提取域名。例如:

x <-"https://*.com/questions/ask"

收件人:*.com

我从这个问题中找到了以下正则表达式。 regex match main domain name

regex <- "([0-9A-Za-z]{2,}\\[0-9A-Za-z]{2,3}\\[0-9A-Za-z]{2,3}|[0-9A-Za-z]{2,}\\[0-9A-Za-z]{2,3})$"

但是当我尝试使用 stringr 包中的 str_extract 时,R 似乎无法理解它。

x2 <- str_extract(x, regex)

【问题讨论】:

  • 您需要非常具体地了解您认为的“域名”。请参阅我的答案下的 cmets。

标签: xml regex r xpath


【解决方案1】:

为什么不使用XML 中的parseURI?它将 URL 分解为不同的元素。

x <- "http://*.com/questions/ask"
library(XML)
parseURI(x)$server
# [1] "*.com"

【讨论】:

  • 服务器不返回根域。不过,我的问题的答案确实如此:*.com/questions/26291025/…,如&gt; parseURI("http://www.*.com/questions/ask")$server 给出[1] "www.*.com"。通常是“www”。返回根域时被忽略。
  • 是的,但这不是问题中显示的示例。我们目前不知道 OP 是否想要保留 www 或删除它。
  • *.com 没有 wwww。将是解析 URL 的理想结果。
【解决方案2】:

TLD 提取并不像您想象的那么简单。有一个nice list 被认为是“公共 TLD”,即实际上什么是真正的*域。我每天都在处理这些问题(为网络安全挖掘域名)。

我们有一个tldextractR package(更多信息here)可以很好地解析这些以进行进一步的数据挖掘。您可以使用httr 中的parse_url 提取hostname 组件,然后对其运行我们的tldextract 函数:

library(httr)
library(rvest)
library(tldextract)

# get some URLs - I encourage you to bump up "10" to "100" or more to see how
# tldextract deals with "public TLDs"
pg <- html("http://httparchive.org/urls.php?start=1&end=10")

# clean up the <pre> output and make it a character list
urls <- pg %>% html_nodes("pre") %>% html_text() %>% strsplit("\n") %>% unlist
urls <- urls[urls != ""] # that site has a blank first line we don't need

# extract the hostname part
urls <- as.character(unlist(sapply(lapply(urls, parse_url), "[", "hostname")))
urls

##  [1] "www.google.com"    "www.facebook.com"  "www.youtube.com"  
##  [4] "www.yahoo.com"     "www.baidu.com"     "www.wikipedia.org"
##  [7] "www.amazon.com"    "www.twitter.com"   "www.qq.com"       
## [10] "www.taobao.com"

# extract the TLDs
tlds <- tldextract(urls)
tlds

##                 host subdomain    domain tld
## 1     www.google.com       www    google com
## 2   www.facebook.com       www  facebook com
## 3    www.youtube.com       www   youtube com
## 4      www.yahoo.com       www     yahoo com
## 5      www.baidu.com       www     baidu com
## 6  www.wikipedia.org       www wikipedia org
## 7     www.amazon.com       www    amazon com
## 8    www.twitter.com       www   twitter com
## 9         www.qq.com       www        qq com
## 10    www.taobao.com       www    taobao com

# piece what we need together
sprintf("%s.%s", tlds$domain, tlds$tld)

##  [1] "google.com"    "facebook.com"  "youtube.com"   "yahoo.com"    
##  [5] "baidu.com"     "wikipedia.org" "amazon.com"    "twitter.com"  
##  [9] "qq.com"        "taobao.com"

【讨论】:

    【解决方案3】:

    您好,此代码用于获取域名并使用 From Regex

    .*(?:\.|\/)(.*)\..*
    

    例如

    http://www.*.com

    结果

    堆栈溢出

    【讨论】: