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

例如,我正在尝试拆分 URL,https://stackoverflow.com/questions/并仅使用stackoverflow.com. 在不使用内置函数的情况下,如何在 Java 中执行此操作getHost()



繁星淼淼
浏览 97回答 3
3回答

梦里花落0921

干得好 :&nbsp; &nbsp; Pattern pattern = Pattern.compile("^(?:(?:http)s?://)?(?<hostGroup>[^/:]+).*");&nbsp; &nbsp; Matcher matcher = pattern.matcher("https://stackoverflow.com/questions/");&nbsp; &nbsp; if (matcher.matches()) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(matcher.group("hostGroup"));&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Not found! Invalid URL ^^");&nbsp; &nbsp; }上面将找到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()!)干杯!

叮当猫咪

如果您可以将 URL 放入字符串中,则有以下选项:public static void main(String []args){&nbsp; String str ="https://stackoverflow.com/questions/";&nbsp; String[] parts = str.split("/");&nbsp; String part1 = parts[0]; //https:&nbsp; String part2 = parts[1]; //'nothing'&nbsp; String part3 = parts[2]; //stackoverflow.com&nbsp; String part4 = parts[3]; //questions}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java