博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C#正则表达式Match类和Group类用法

Posted on 2011-05-04 23:04  moss_tan_jun  阅读(4749)  评论(0编辑  收藏  举报

==============================

MatchCollection mc = Regex.Matches("A12493", "[A-Za-z]");
            foreach (Match m in mc)
            {
                string a = Convert.ToString(m.Groups["0"].Value);
            }

 

 

============================================================

下面通过例子演示如何将上面的UBB编码转换成HTML代码:


 /// 
  /// 下面的代码实现将文本中的UBB超级链接代码替换为HTML超级链接代码
  /// 
  public void UBBDemo()
  {
   string text = "[url=http://zhoufoxcn.blog.51cto.com][/url][url=http://blog.csdn.net/zhoufoxcn]周公的专栏[/url]";
   Console.WriteLine("原始UBB代码:" + text);
   Regex regex = new Regex(@"(\[url=([ \S\t]*?)\])([^[]*)(\[\/url\])", RegexOptions.IgnoreCase);
   MatchCollection matchCollection = regex.Matches(text);
   foreach (Match match in matchCollection)
   {
   string linkText = string.Empty;
   //如果包含了链接文字,如第二个UBB代码中存在链接名称,则直接使用链接名称
   if (!string.IsNullOrEmpty(match.Groups[3].Value))
   {
   linkText = match.Groups[3].Value;
   }
   else//否则使用链接作为链接名称
   {
   linkText = match.Groups[2].Value;
   }
   text = text.Replace(match.Groups[0].Value, "" + linkText + "");
   }
   Console.WriteLine("替换后的代码:"+text);
  
  }

  程序执行结果如下:

  原始UBB代码:[url=http://zhoufoxcn.blog.51cto.com][/url][url=http://blog.csdn.net/zhoufoxcn]周公的专栏[/url]

  替换后的代码:http://zhoufoxcn.blog.51cto.com周公的专栏

  上面的这个例子就稍微复杂点,对于初学正则表达式的朋友来说,可能有点难于理解,不过没有关系,后面我会讲讲正则表达式。在实际情况下,可能通过match.Groups[0].Value这种方式不太方便,就想在访问DataTable时写string name=dataTable.Rows[i][j]这种方式一样,一旦再次调整,这种通过索引的方式极容易出错,实际上我们也可以采用名称而不是索引的放来来访问Group分组,这个也会在以后的篇幅中去讲。