Java提取字符串中的域名或ip


String hostIP = "http://www.baidu.com/s/t";
hostIP = hostIP.replace("http://","").replace("https://","");//去除http和https前綴
String [] arr = hostIP.split("/");//按‘/’分隔,取第一個
hostIP = arr[0];

 

正則提取:

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM