zoukankan      html  css  js  c++  java
  • C# Regex类用法

    使用Regex类需要引用命名空间:using System.Text.RegularExpressions;
    
    利用Regex类实现验证
    
    示例1:注释的代码所起的作用是相同的,不过一个是静态方法,一个是实例方法
    
    var source = "刘备关羽张飞孙权";
     //Regex regex = new Regex("孙权");
     //if (regex.IsMatch(source))
     //{
     // Console.WriteLine("字符串中包含有敏感词:孙权!");
     //}
    if (Regex.IsMatch(source, "孙权")) 
     {
      Console.WriteLine("字符串中包含有敏感词:孙权!");
     }
    Console.ReadLine();
    
    示例2:使用带两个参数的构造函数,第二个参数指示忽略大小写,很常用
    
    var source = "123abc345DEf";
     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
  • 相关阅读:
    AndroidUI组件之ListView小技巧
    iframe属性參数
    Applet 数字签名技术全然攻略
    SoftReference
    递归算法浅谈
    VS2010 打包生成exe文件后 执行安装文件出现 TODO:&lt;文件说明&gt;已停止工作并已关闭
    创建新的Cocos2dx 3.0项目并解决一些编译问题
    ORACLE触发器具体解释
    SRM 624 D2L3: GameOfSegments, 博弈论,Sprague–Grundy theorem,Nimber
    cidaemon.exe进程cpu占用率高及关闭cidaemon.exe进程方法
  • 原文地址:https://www.cnblogs.com/william-lin/p/4025962.html
Copyright © 2011-2022 走看看