详解C#正则表达式Regex常用匹配
使用Regex类需要引用命名空间:usingSystem.Text.RegularExpressions;
一、利用Regex类实现验证
示例1:注释的代码所起的作用是相同的,不过一个是静态方法,一个是实例方法
varsource="刘备关羽张飞孙权何问起";
//Regexregex=newRegex("孙权");
//if(regex.IsMatch(source))
//{
//Console.WriteLine("字符串中包含有敏感词:孙权!");
//}
if(Regex.IsMatch(source,"孙权"))
{
Console.WriteLine("字符串中包含有敏感词:孙权!");
}
Console.ReadLine();
示例2:使用带两个参数的构造函数,第二个参数指示忽略大小写,很常用
varsource="123abc345DEf";
Regexregex=newRegex("def",RegexOptions.IgnoreCase);
if(regex.IsMatch(source))
{
Console.WriteLine("字符串中包含有敏感词:def!");
}
Console.ReadLine();
二、使用Regex类进行替换
示例1:简单情况
varsource="123abc456ABC789";
//静态方法
//varnewSource=Regex.Replace(source,"abc","|",RegexOptions.IgnoreCase);
//实例方法
Regexregex=newRegex("abc",RegexOptions.IgnoreCase);
varnewSource=regex.Replace(source,"|");
Console.WriteLine("原字符串:"+source);
Console.WriteLine("替换后的字符串:"+newSource);
Console.ReadLine();
结果:
原字符串:123abc456ABC789
替换后的字符串:123|456|789
示例2:将匹配到的选项替换为html代码,我们使用了MatchEvaluator委托
varsource="123abc456ABCD789";
Regexregex=newRegex("[A-Z]{3}",RegexOptions.IgnoreCase);
varnewSource=regex.Replace(source,newMatchEvaluator(OutPutMatch));
Console.WriteLine("原字符串:"+source);
Console.WriteLine("替换后的字符串:"+newSource);
Console.ReadLine();
//柔城
privatestaticstringOutPutMatch(Matchmatch)
{
return"<b>"+match.Value+"</b>";
}
输出:
原字符串:123abc456ABCD789
替换后的字符串:123<b>abc</b>456<b>ABC</b>D789
三、C#正则表达式Regex常用匹配
#region身份证号码正则表达式
//何问起
Console.WriteLine("请输入一个身份证号码");
stringid=Console.ReadLine();
boolb4=Regex.IsMatch(id,@"^\d{15}|\d{18}$");
boolb5=Regex.IsMatch(id,@"^(\d{15}|\d{18})$");
Console.WriteLine(b4);
Console.WriteLine(b5);
#endregion
#region匹配电话号码
//hovertree
Console.WriteLine("请输入电话号码");
stringphone=Console.ReadLine();
boolb=Regex.IsMatch(phone,@"^((\d{3,4}\-\d?{7,8})|(\d{5}))$");
Console.WriteLine(b);
#endregion
#region匹配email的regex
//hovertree
Console.WriteLine("请输入Email地址");
stringemail=Console.ReadLine();
boolbhvt=Regex.IsMatch(email,@"^\w+@\w+\.\w+$");
Console.WriteLine(bhvt);
#endregion
#region匹配ip地址的regex
//hovertree
Console.WriteLine("请输入一个IP地址");
stringip=Console.ReadLine();
boolbkly=Regex.IsMatch(ip,@"^\d{1,3}(\.\d{1,3}){3}$");
Console.WriteLine(bkly);
#endregion
#region匹配日期合法regex
//何问起
Console.WriteLine("请输入一个日期");
stringdate=Console.ReadLine();
boolbhovertree=Regex.IsMatch(date,@"^\d{4}\-\d{1,2}\-\d{1,2}$");
Console.WriteLine(bhovertree);
#endregion
#region匹配url地址的regex
//"http://hovertree.com"
//"http://keleyi.com/a/bjae/h1o76nuh.htm?id=3&name=aaa"
//"https://s.taobao.com/search?q=hover+tree&js=1&stats_click=search_radio_all%3A1&initiative_id=staobaoz_20151204&ie=utf8"
//"ftp://127.0.0.1/myslider.txt"
//hovertree
Console.WriteLine("请输入url地址");
stringurl=Console.ReadLine();
boolbkeleyi=Regex.IsMatch(url,@"^[a-zA-Z]+://.+$");
Console.WriteLine(bkeleyi);
#endregion
以上就是关于C#正则表达式Regex常用匹配的详细介绍,希望对大家的学习有所帮助。