四联光电智能照明论坛

标题: C# Regex类用法 [打印本页]

作者: admin    时间: 2016-11-7 09:43
标题: C# Regex类用法

使用Regex类需要引用命名空间:using System.Text.RegularExpressions;
利用Regex类实现验证
示例1:注释的代码所起的作用是相同的,不过一个是静态方法,一个是实例方法
  1. var source = "刘备关羽张飞孙权";
  2. //Regex regex = new Regex("孙权");
  3. //if (regex.IsMatch(source))
  4. //{
  5. // Console.WriteLine("字符串中包含有敏感词:孙权!");
  6. //}
  7. if (Regex.IsMatch(source, "孙权"))
  8. {
  9.   Console.WriteLine("字符串中包含有敏感词:孙权!");
  10. }
  11. Console.ReadLine();
复制代码


示例2:使用带两个参数的构造函数,第二个参数指示忽略大小写,很常用
  1. var source = "123abc345DEf";
  2. Regex regex = new Regex("def",RegexOptions.IgnoreCase);
  3. if (regex.IsMatch(source))
  4. {
  5.   Console.WriteLine("字符串中包含有敏感词:def!");
  6. }
  7. Console.ReadLine();
复制代码


使用Regex类进行替换

示例1:简单情况
  1. var source = "123abc456ABC789";
  2. // 静态方法
  3. //var newSource=Regex.Replace(source,"abc","|",RegexOptions.IgnoreCase);
  4. // 实例方法
  5. Regex regex = new Regex("abc", RegexOptions.IgnoreCase);
  6. var newSource = regex.Replace(source, "|");
  7. Console.WriteLine("原字符串:"+source);
  8. Console.WriteLine("替换后的字符串:" + newSource);
  9. Console.ReadLine();
复制代码


结果:
原字符串:123abc456ABC789
替换后的字符串:123|456|789

示例2:将匹配到的选项替换为html代码,我们使用了MatchEvaluator委托
  1. var source = "123abc456ABCD789";
  2. Regex regex = new Regex("[A-Z]{3}", RegexOptions.IgnoreCase);
  3. var newSource = regex.Replace(source,new MatchEvaluator(OutPutMatch));
  4. Console.WriteLine("原字符串:"+source);
  5. Console.WriteLine("替换后的字符串:" + newSource);
  6. Console.ReadLine();

  7. private static string OutPutMatch(Match match)
  8. {
  9.   return "<b>" +match.Value+ "</b>";
  10. }
复制代码


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





欢迎光临 四联光电智能照明论坛 (http://5xhome.com/) Powered by Discuz! X3.2