为了账号安全,请及时绑定邮箱和手机立即绑定

如何分割 URL 并仅获取主机名

如何分割 URL 并仅获取主机名

繁星淼淼 2024-01-25 10:46:58
例如,我正在尝试拆分 URL,https://stackoverflow.com/questions/并仅使用stackoverflow.com. 在不使用内置函数的情况下,如何在 Java 中执行此操作getHost()?
查看完整描述

3 回答

?
梦里花落0921

TA贡献1772条经验 获得超5个赞

干得好 :


    Pattern pattern = Pattern.compile("^(?:(?:http)s?://)?(?<hostGroup>[^/:]+).*");

    Matcher matcher = pattern.matcher("https://stackoverflow.com/questions/");


    if (matcher.matches()) {

        System.out.println(matcher.group("hostGroup"));

    } else {

        System.out.println("Not found! Invalid URL ^^");

    }

上面将找到stackoverflow.com的以下 url 字符串:

  • https://stackoverflow.com/questions/

  • http://stackoverflow.com/questions/

  • stackoverflow.com/questions/

  • stackoverflow.com:80/questions/

  • stackoverflow.com/

  • stackoverflow.com

我想那是为了练习正则表达式?否则,尽可能使用标准 API -(根据您的情况URI#getHost()!)

干杯!


查看完整回答
反对 回复 2024-01-25
?
叮当猫咪

TA贡献1776条经验 获得超12个赞

如果您可以将 URL 放入字符串中,则有以下选项:


public static void main(String []args){

  String str ="https://stackoverflow.com/questions/";

  String[] parts = str.split("/");

  String part1 = parts[0]; //https:

  String part2 = parts[1]; //'nothing'

  String part3 = parts[2]; //stackoverflow.com

  String part4 = parts[3]; //questions

}


查看完整回答
反对 回复 2024-01-25
  • 3 回答
  • 0 关注
  • 48 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信