gpt4 book ai didi

java - 如何从任意字符串 url 获取网站名称

转载 作者:行者123 更新时间:2023-12-01 17:09:55 25 4
gpt4 key购买 nike

我已经给出了包含任何有效网址的字符串。我必须从给定的网址中找到网站的名称。我也忽略了子域。

喜欢

http://www.yahoo.com   =>    yahoo
www.google.co.in => google
http://in.com => in
http://india.gov.in/ => india
https://in.yahoo.com/ => yahoo
http://philotheoristic.tumblr.com/ =>tumblr
http://philotheoristic.tumblr.com/
https://in.movies.yahoo.com/ =>yahoo

如何做到这一点

最佳答案

您可以使用URL

来自文档 - http://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html

import java.net.*;
import java.io.*;

public class ParseURL {
public static void main(String[] args) throws MalformedURLException {

URL aURL = new URL("http://example.com:80/docs/books/tutorial"
+ "/index.html?name=networking#DOWNLOADING");

System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());
}
}

这是程序显示的输出:

protocol = http
authority = example.com:80
host = example.com // name of website
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING

因此,通过使用aURL.getHost()您可以获取网站名称。要忽略子域,您可以使用 "." 将其拆分,因此它变为 aURL.getHost().split(".")[0] 以仅获取名称。

关于java - 如何从任意字符串 url 获取网站名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24237036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com