C#正则表达式的Regex类用法

[代码] c#代码

01 /// <summary>
02 /// 检查字符串中是否有“孙权”这个敏感词
03 /// </summary>
04 public void IsMatchDemo()
05 {
06      string source = "刘备ABC关羽ABc张飞Abc赵云abc诸葛亮aBC孙权abC周瑜AbC鲁肃aBc曹操许攸郭嘉需晃袁绍" ;
07      Regex regex = new Regex( "孙权" );
08      //if (Regex.IsMatch(source, "孙权"))
09      //下面这句和上面被注释掉的一句作用的同样的
10      if (regex.IsMatch(source))
11      {
12          Console.WriteLine( "字符串中包含有敏感词:孙权!" );
13      }

[代码] c#代码

01 /// <summary>
02 /// 检查字符串中是否有“def”的任何大小写形式
03 /// </summary>
04 public void IsMatchDemoWithOption()
05 {
06      string source = "刘备ABC关羽ABc张飞Abc赵云abc诸葛亮aBC孙权abC周瑜AbC鲁肃aBc曹操DEF许攸郭嘉需晃袁绍" ;
07      Regex regex = new Regex( "def" ,RegexOptions.IgnoreCase);
08      if (regex.IsMatch(source))
09      {
10          Console.WriteLine( "字符串中包含有敏感词:def!" );
11      }
12 }

[代码] c#代码

1 Regex regex = new Regex( "孙权" );
2 //if (Regex.IsMatch(source, "孙权"))
3 //下面这句和上面被注释掉的一句作用的同样的
4 if (regex.IsMatch(source))

[代码] c#代码

01 /// <summary>
02 /// 实现字符串替换功能
03 /// </summary>
04 public void Replace()
05 {
06      string source = "刘备ABC关羽ABc张飞Abc赵云abc诸葛亮aBC孙权abC周瑜AbC鲁肃aBc曹操DEF许攸郭嘉需晃袁绍" ;
07      Regex regex = new Regex( "abc" , RegexOptions.IgnoreCase);
08      string result=regex.Replace(source, "|" );
09      Console.WriteLine( "原始字符串:" + source);
10      Console.WriteLine( "替换后的字符串:" + result);
11 }

[代码] c#代码

01 /// <summary>
02 /// 实现字符串替换功能
03 /// </summary>
04 public void ReplaceMatchEvaluator()
05 {
06      string source = "刘备ABC关羽ABc张飞Abc赵云abc诸葛亮aBC孙权abC周瑜AbC鲁肃aBc曹操DEF许攸郭嘉需晃袁绍" ;
07      Regex regex = new Regex( "[A-Z]{3}" , RegexOptions.IgnoreCase);
08      string result = regex.Replace(source, new MatchEvaluator(OutPutMatch));
09      Console.WriteLine( "原始字符串:" + source);
10      Console.WriteLine( "替换后的字符串:" + result);
11 }
12 /// <summary>
13 /// MatchEvaluator委托中调用的方法,可以对匹配结果进行处理
14 /// </summary>
15 /// <param name="match">操作过程中的单个正则表达式匹配</param>
16 /// <returns></returns>
17 private string OutPutMatch(Match match)
18 {
19      return "<b>" + match.Value + "</b>" ;
20 }

这里面仅介绍在C#中如何使用正则表达式,以抛砖引玉之用,而具体的正则表达式需要在实际应用中积累。最后分享一个正则表达式的测试工具,见网址:http://www.oschina.net/p/regex+tester

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值