String hostIP = "http://www.baidu.com/s/t"; hostIP = hostIP.replace("http://","").replace("https://","");//去除http和https前綴 String [] arr = hostIP.split("/");//按‘/’分隔,取第一個 hostIP = arr[0];
正則提取:html
String host1 = ""; Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+"); Matcher matcher = p.matcher(" 10.135.12.32/codes.html#multiple_bindings"); if (matcher.find()) { host1 = matcher.group(); } System.out.println(host1);
使用java標準類庫java.net.URL java.net.URL url = new java.net.URL("https://i.cnblogs.com/EditPosts.aspx?postid=9007907"); String host = url.getHost();// 獲取主機名 System.out.println("host:"+host);// 結果 blog.csdn.net