zoukankan      html  css  js  c++  java
  • C#正则表达式Match类和Group类用法

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

    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分组,这个也会在以后的篇幅中去讲。

  • 相关阅读:
    yii2之依赖注入与依赖注入容器
    MySQL查询性能优化
    MySQL索引(2)
    go es
    es数据操作入门
    es环境搭建
    gRPC接入etcd
    etcd简单介绍
    Go调用NSQ简单实践
    NSQ快速入门实践
  • 原文地址:https://www.cnblogs.com/moss_tan_jun/p/2037073.html
Copyright © 2011-2022 走看看