C#RegexMatch類和Group類用法

來源:互聯網
上載者:User

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

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周公的專欄

  上面的這個例子就稍微複雜點,對於初學Regex的朋友來說,可能有點難於理解,不過沒有關係,後面我會講講Regex。在實際情況下,可能通過match.Groups[0].Value這種方式不太方便,就想在訪問DataTable時寫string name=dataTable.Rows[i][j]這種方式一樣,一旦再次調整,這種通過索引的方式極容易出錯,實際上我們也可以採用名稱而不是索引的放來來訪問Group分組,這個也會在以後的篇幅中去講。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.