博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#域名操作,正则匹配域名
阅读量:4289 次
发布时间:2019-05-27

本文共 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...";    List
list = RegexHelper.MatchsDomain(source); foreach (var item in list) { Console.WriteLine(item); }}

更多参考:

你可能感兴趣的文章
Windows 上安装 MySQL
查看>>
eclipse 的mybatis中mapper.xml文件标签没有提示的解决方法
查看>>
linux 上一主两从mysql集群中某台数据库宕机解决方法
查看>>
大牛面试指南
查看>>
android入门(一)---UI组件之文本框(TextView)
查看>>
演示动画怎么实现的
查看>>
android入门---Activity组件.活动(一)
查看>>
Android入门---GridView组件
查看>>
获取apk文件上的精美图片素材
查看>>
RelativeLayout中Margin属性
查看>>
JAVA中文乱码解决方法
查看>>
端口号占用问题 serveral ports(8080,8009) are already in use
查看>>
浅析JAVA的抽象和接口
查看>>
SeekBar控件入门
查看>>
SharedPreference存储实战之记住登陆账号密码
查看>>
如何在项目的任何地方轻松获取到全局状态信息Context
查看>>
ListView控件性能提升
查看>>
android下拉刷新功能---教你实现简单的ListView下拉刷新
查看>>
ListView分页展示数据功能一(按钮方式)
查看>>
Android四大组件之服务(一)-----服务基础功能简述
查看>>