美文网首页
通过URL地址获取主域名

通过URL地址获取主域名

作者: Anchoriter | 来源:发表于2018-10-29 12:02 被阅读15次

例如:http://www.baidu.comhttps://www.baidu.comhttps://m.baidu.comwww.baidu.comm.baidu.com获取到的主域名为baidu.com

/// 获取主域名
+(NSString *)getRootDomainWithUrl:(NSString *)url{
    NSString *domain = nil;
    // 主域名正则
    NSString * pattern = @"[\\w-]+\\.(com.cn|com.hk|net.cn|gov.cn|org.cn|com|net|org|gov|cc|biz|info|cn|co|tv|mobi|me|name|asia|hk|ac.cn|bj.cn|sh.cn|tj.cn|cq.cn|he.cn|sx.cn|nm.cn|ln.cn|jl.cn|hl.cn|js.cn|zj.cn|ah.cn|fj.cn|jx.cn|sd.cn|ha.cn|hb.cn|hn.cn|gd.cn|gx.cn|hi.cn|sc.cn|gz.cn|yn.cn|xz.cn|sn.cn|gs.cn|qh.cn|nx.cn|xj.cn|tw.cn|hk.cn|mo.cn|travel|tw|com.tw|la|sh|ac|io|ws|us|tm|vc|ag|bz|in|mn|sc|co|org.tw|jobs|tel|网络|公司|中国)\\b()*";
    NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
    // 获取主域名字符串的范围
    NSTextCheckingResult *match = [regex firstMatchInString:url options:0 range:NSMakeRange(0, [url length])];
    if (match) {// 截获主域名
        domain = [url substringWithRange:match.range];
    }
    return domain;
}

相关文章

网友评论

      本文标题:通过URL地址获取主域名

      本文链接:https://www.haomeiwen.com/subject/cghbtqtx.html