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

    技术2025-03-17  16

    [代码] 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)