本文共 1978 字,大约阅读时间需要 6 分钟。
一、判断一个字符串是否是域名
///实例验证:/// 验证字符串是否是域名/// /// 指定字符串///public static bool IsDomain(string str){ string pattern = @"^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$"; return IsMatch(pattern, str);}/// /// 判断一个字符串,是否匹配指定的表达式(区分大小写的情况下)/// /// 正则表达式/// 要匹配的字符串///public static bool IsMatch(string expression, string str){ Regex reg = new Regex(expression); if (string.IsNullOrEmpty(str)) return false; return reg.IsMatch(str);}
////// 说明,目前不支持中文域名/// public static void TestOne(){ Console.WriteLine(RegexHelper.IsDomain("baidu.com"));//true Console.WriteLine(RegexHelper.IsDomain("m.baidu.com"));//true Console.WriteLine(RegexHelper.IsDomain("m.bj.baidu.com"));//true Console.WriteLine(RegexHelper.IsDomain("baidu.com."));//false Console.WriteLine(RegexHelper.IsDomain("m.baidu.com.cn"));//true Console.WriteLine(RegexHelper.IsDomain("m.百度.com"));//false}
二、匹配字符串中的域名:
///验证实例:/// 匹配获取字符串中所有的域名/// /// ///public static List MatchsDomain(string input){ string pattern = @"[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+"; return Matchs(input, pattern);}/// /// 匹配结果 返回匹配结果的数组/// /// /// ///public static List Matchs(string input, string expression){ List list = new List (); MatchCollection collection = Regex.Matches(input, expression, RegexOptions.IgnoreCase | RegexOptions.Multiline); foreach (Match item in collection) { if (item.Success) { list.Add(item.Value); } } return list;}
public static void TestTwo(){ string source = "123.com zhidao.123.com www.123.com/q?ct=17&pn=0&tn zhidao.123.com/q?ct=17&pn=0&tn 123.com/q?ct=17&pn=0&tn 要求匹配出123.com 或者有可能是这样的有不是顶级域名的 www.123.com.cn zhidao.123.com.cn www.123.co..."; Listlist = RegexHelper.MatchsDomain(source); foreach (var item in list) { Console.WriteLine(item); }}
更多参考: