C#中的Regex

來源:互聯網
上載者:User

      Regex是我喜歡的東西,Regex在字串處理方面,除了效能問題外,它有著無可比擬的優勢。C#中引入了Regex的類庫,給我們帶來了很大的方便。
      要在C#中使用Regex,需要引用如下的名字空間:

      using System.Text;
      using System.Text.RegularExpressions;

      在C#中使用Regex,最重要的類是Regex。Regex對象的建構函式參數中最常見的一個是Regex的串,另外一個經常使用的是RegexOptions。Regex的字串和Regex的文法這裡就不羅嗦了,大家有興趣的話,可以給我寫郵件和我討論討論。關於RegexOptions,下面是其中一些主要參數的介紹:
      RegexOptions.Compiled         讓C#把Regex編譯成一個Assembly,這樣可以在執行正則的時候啟動的更快。這個參數需要注意的事情是,使用這個選項時,Regex一定是靜態字串,而不能使動態字串(可以想象,動態字串是不會有任何效果的)。
      RegexOptions.IgnoreCase      讓Regex匹配的時候忽略大小寫。
      RegexOptions.Multiline           多行模式正則匹配。
      RegexOptions.None               不指定任何的選項。
      RegexOptions.RightToLeft      從右向左開始匹配。
      RegexOptions.SingleLine        單行模式正則匹配。

      下面討論Regex的使用:
       Regex token = new Regex(@"((?<protocol>[a-zA-Z]*?)://)?(?<domain>[^/]*)(?<path>.*)", RegexOptions.Compiled);
       Match matchList = token.Match("http://www.sina.com.cn/index.html");

       if (matchList.Success)
       {
                Console.WriteLine( "Protocol:{0},Domain:{1},Path:{2}" ,
                        matchList.Groups["protocol"] ,
                        matchList.Groups["domain"] ,
                        matchList.Groups["path"]) ;
       }
      
      上面的是匹配單行的情況,下面的例子是示範的匹配多個結果的情況:

       Regex token = new Regex(@"\s*((?<protocol>\w*?)://)?(?<domain>[^\/\s]+)(?<path>[^\s]*)", RegexOptions.Compiled);
       MatchCollection matches = token.Matches("http://www.sina.com.cn/index.html http://www.microsoft.com ftp://ftp.cav.com/info.zip");

       if (matches.Count != 0)
       {
                foreach (Match matchList in matches)
                {
                    Console.WriteLine("Protocol:{0},Domain:{1},Path:{2}",
                            matchList.Groups["protocol"],
                            matchList.Groups["domain"],
                            matchList.Groups["path"]);

                    foreach (Capture c in matchList.Captures)
                    {
                        Console.WriteLine("Capture:[" + c + "]");
                    }
                }
       }

      下面是一個Replace的用法,主要目的是為了示範MatchEvaluator.
       public static string ReplaceEva(Match match)
       {
            return match.Groups["protocol"].Value + "://" + "www.google.com/" + match.Groups["path"].Value;
       }

      Regex token = new Regex(@"\s*((?<protocol>\w*?)://)?(?<domain>[^\/\s]+)(?<path>[^\s]*)", RegexOptions.Compiled);
      string strNew = token.Replace("www.sohu.com/index.htm",new MatchEvaluator(ReplaceEva));
      Console.WriteLine("New Line:{0}", strNew);

      MatchEvaluator是一個函數代理,用來處理替換過程中得到的每一個Match。返回的字串就是替換後的字串。

      最後示範以下最簡單的使用正則進行Splite的操作,例子代碼如下:

      Regex r = new Regex("(-)"); 
      string[] s = r.Split("one-two-banana");

      OK, That's all.希望能夠對大家有所協助。
           

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.