使用正则表达式,如何提取顶级域名?

Using Regex, how can I pull out the top-level domain name?

我需要创建一个高效的正则表达式(最少的回溯)来从一些日志中提取顶级域名。 URL 可能是四种类型之一,所以我需要以下内容:

  1. "website.ca/somepage"
  2. 中提取website.ca
  3. "https://subdomain.website.com/somepage"
  4. 中提取 website.com
  5. "10.10.10.10/somepage"
  6. 中提取 10.10.10.10
  7. "myserver/somepage"
  8. 中提取myserver

我有一个半可行的解决方案,但遗漏了一些。

"[^"]*(\w+\.[a-z]+|\d+\.\d+\.\d+\.\d+)\/

有人有什么建议吗?

试试这个正则表达式:

([a-zA-Z0-9]+\.[a-zA-Z]+|[0-9\.]+|[a-zA-Z0-9]+)(?=\/)

您可以在 regex101.com 进行测试:https://regex101.com/r/dK0bJ7/4

第 1 场比赛:website.com
第 2 场:10.10.10.10
第 3 场:myserver
第 4 场:website.ca