c# 第五课 regex

使用Regex类需要引用命名空间:using System.Text.RegularExpressions;

利用Regex类实现验证

示例1:注释的代码所起的作用是相同的,不过一个是静态方法,一个是实例方法

var source = "abcdefg";            

//Regex regex = new Regex("abc");            

//if (regex.IsMatch(source))            

//{            

//    Console.WriteLine("字符串中包含有敏感词:abc!");            

//} if (Regex.IsMatch(source, "abc"))            

{   Console.WriteLine("字符串中包含有敏感词:abc!");         

    } Console.ReadLine();

示例2:使用带两个参数的构造函数,第二个参数指示忽略大小写,很常用

var source = "123DEf";            

Regex regex = new Regex("def",RegexOptions.IgnoreCase);            

if (regex.IsMatch(source))            

{   Console.WriteLine("字符串中包含有敏感词:def!");            

} Console.ReadLine();

 

使用Regex类进行替换

示例1:简单情况

var source = "123abc456ABC789";            

// 静态方法 //var newSource=Regex.Replace(source,"abc","|",RegexOptions.IgnoreCase);            

// 实例方法 Regex regex = new Regex("abc", RegexOptions.IgnoreCase);            

var newSource = regex.Replace(source, "|");            

Console.WriteLine("原字符串:"+source);            

Console.WriteLine("替换后的字符串:" + newSource);            

Console.ReadLine();

结果:

原字符串:123abc456ABC789

替换后的字符串:123|456|789

 

示例2:将匹配到的选项替换为html代码,我们使用了MatchEvaluator委托

var source = "123abc456ABCD789";            

Regex regex = new Regex("[A-Z]{3}", RegexOptions.IgnoreCase);            

var newSource = regex.Replace(source,new MatchEvaluator(OutPutMatch));            

Console.WriteLine("原字符串:"+source);            

Console.WriteLine("替换后的字符串:" + newSource);           

  Console.ReadLine();

 

private static string OutPutMatch(Match match)        

{   return "<b>" +match.Value+ "</b>";         }

输出:

原字符串:123abc456ABCD789

替换后的字符串:123<b>abc</b>456<b>ABC</b>D789

转载于:https://www.cnblogs.com/GSONG/p/4440065.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值