获取一级域名

  项目中需要增加获取一级域名的方法,自己借鉴网上前辈们的资料,改变成符合需求的。

  分享给大家,有歧义的地方大家共同研讨,共同学习。有不足的地方,或各位有更好的见解,请多多指教!

 1 import java.util.ArrayList;
 2 import java.util.List;
 3 import java.util.regex.Matcher;
 4 import java.util.regex.Pattern;
 5 
 6 public class GetOneYM {
 7     /*    
 8      *  匹配正则
 9      *  需求中有IP格式的域名
10      *  
11      */
12     private static String regex="([\w][\w-]*\."
13             + "(?:com\.cn|com|cn|co|edu|net|org|gov|cc|biz|tv|info)(\/|$))"
14             + "|(((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}"
15             + "(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))))";
16     
17     public static String getOneYM(String url){
18         Pattern p = Pattern.compile(regex);  
19         /*
20           * 如果域名中有端口号,去除
21          */
22         int index = url.indexOf(":");
23         if (index != -1) {
24             url = url.substring(0, index).trim();
25         }
26         Matcher m = p.matcher(url); 
27         List<String> strList = new ArrayList<String>();
28             while(m.find()){
29             strList.add(m.group());
30         }
31         String categoryId = strList.toString();
32         categoryId = categoryId.substring(1,categoryId.length()-1);
33         return categoryId;
34     }
35 }
原文地址:https://www.cnblogs.com/yinchengzhe/p/4707358.html