C#中Regex小例

來源:互聯網
上載者:User
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Text.RegularExpressions;
  5. namespace 字串
  6. {
  7.     class Regex
  8.     {
  9.         public static void Main()
  10.         {
  11.             //Regex是用來簡化字串操作的,一般正則所實現的功能,用方法也一樣可以,只是方法有可能就會變的很複雜!
  12.             //假定我們要在字串中做一次純檔案的搜尋,不用任何的正則串。
  13.             string Text = @"This comprehensive compendium provides a boroad and thor
  14.                             This comprehensive compendium provides a boroad and thor
  15.                             This comprehensive compendium provides a boroad and thor
  16.                             This comprehensive compendium provides a boroad and thor
  17.                             This comprehensive compendium provides a boroad and thor";
  18.             string Pattern = "thor";
  19.             MatchCollection Matchs = Regex.Matches( Text , Pattern , RegexOptions.IgnoreCase );
  20.             foreach (Match i in Matchs)
  21.             {
  22.                 Console.WriteLine( i.Value );
  23.             }
  24.             
  25.             //例:我們要查看我們的單詞是不是以N開頭
  26.             string myText = "Naladdin";
  27.             Match mat = Regex.Match( myText , @"/bn" , RegexOptions.IgnoreCase );
  28.             Console.WriteLine(myText + "是否以N開頭" + mat.Success);
  29.             //以A開頭,以ion結尾 
  30.             string myText2 = "Applaldafaslkdfasd;fasdfasdfasdfadsfadfadsfication";
  31.             Match mat2 = Regex.Match(myText2, @"/ba/S*ion/b", RegexOptions.IgnoreCase);
  32.             Console.WriteLine(myText2 + "是否以A開頭Ion結尾,任意長度的單詞" + mat2.Success);
  33.             Console.ReadLine();
  34.             
  35.         }
  36.     }
  37. }

聯繫我們

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