c#正则提取和替换

  1. /// <summary>  
  2. /// 正则表达式提取和替换内容  
  3. /// </summary>  
  4. public static string Contentextract()  
  5. {  
  6.     string result = "";  
  7.     string str = "大家好! <User EntryTime='2010-10-7' Email='zhangsan@163.com'>张三</User> 自我介绍。";  
  8.     Regex regex = new Regex(@"<Users*EntryTime='(?<time>[sS]*?)'s+Email='(?<email>[sS]*?)'>(?<userName>[sS]*?)</User>", RegexOptions.IgnoreCase);  
  9.     Match match = regex.Match(str);  
  10.     if(match.Success)  
  11.     {  
  12.         string userName = match.Groups["userName"].Value;   //获取用户名  
  13.         string time = match.Groups["time"].Value;           //获取入职时间  
  14.         string email = match.Groups["email"].Value;         //获取邮箱地址  
  15.         string strFormat = String.Format("我是:{0},入职时间:{1},邮箱:{2}", userName, time, email);  
  16.         result = regex.Replace(str, strFormat);    //替换内容  
  17.         Console.WriteLine(result);    
  18.     }  
  19.     return result;   //结果:大家好!我是张三,入职时间:2010-10-7,邮箱:zhangsan@163.com 自我介绍。  
原文地址:https://www.cnblogs.com/zhangweixin/p/4071687.html