[英]Java regex to extract host name and domain name from a URL
我已经查看并尝试了多个其他线程,但对我不起作用。 我需要正则表达式解决方案才能使其工作,并且没有 java 代码可以在没有正则表达式的情况下执行此操作。
我已经检查过的一些线程: Get domain name from given url , Extract host name/domain name from URL string和ZD52387880E1EA22817A72D375921381 提取域名? 没有一个对我有用,要么正则表达式不起作用,要么解决方案是没有正则表达式的 java 代码。
我想做什么?
Case 1:
Input: https://api.twitter.com/blog/category/2?user=42&status=enabled
Output: api.twitter.com
Input: abc.xyz.com/blog/category/2?user=42&status=enabled
Output: abc.xyz.com
Case 2:
Input: https://abc.xyz.com/blog/category/2?user=42&status=enabled
Output: xyz.com
Input: abc.xyz.com/blog/category/2?user=42&status=enabled
Output: xyz.com
我需要 2 个正则表达式来解决上述每种情况。 如果可以一次性完成,即使这样也行。
我从第一篇文章中尝试了以下正则表达式:
^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
当有https://
或任何方案但当 URL 中没有方案时,此方案有效。
到目前为止,我正在使用两步解决方案解决第一个案例。
Step 1: Replace scheme
(.*://)(.*) -> $2
remove anything before and including string "://"
Step 2: Extract host name
([^/]*)(.*) -> $1
The first group extracts everything that is before the first "/". Basically extracting everything that isn't slash till I see the first one.
您可以将此正则表达式与可选匹配项和捕获组一起使用:
^(?:\w+://)?((?:[^./?#]+\.)?([^/?#]+))
正则表达式详细信息:
^
: 开始(?:\w+://)?
: 可选匹配方案名称,后跟://
(
: 开始捕获组 #1
(?:[^./?#]+\.)?
:可选地使用非捕获组匹配域名的第一部分([^/?#]+)
:匹配任何不是/
的字符的 1+ , ?
, #
在捕获组 #2)
: 结束捕获组 #1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.