C#中Regex的簡單使用

來源:互聯網
上載者:User

標籤:

C#中有關Regex的類包含在System.Text.RegularExpressions命名空間中,可通過一下代碼添加該命名空間:

1 using System.Text.RegularExpressions;
View Code

字串匹配中,主角是"被匹配串"和"匹配模式"。

 1 // 定義 "被匹配串" 2 string message = " mother father sister brother "; 3 // 定義 "匹配模式" 4 string pattern = @"\b(\w+)ther\b"; 5 // 用靜態方法進行匹配,也可以通過建立正則對象進行匹配 6 MatchCollection matches = Regex.Matches(message, pattern); 7 // 遍曆得到的結果 8 foreach (Match match in matches) { 9     Console.WriteLine("Groups[0].Value = {0} --- Groups[1].Value = {1}", match.Groups[0].Value, matchGroups[1].Value); 10 } 11 12 // 輸出13 // Groups[0].Value = mother --- Groups[1].Value = mo14 // Groups[0].Value = father --- Groups[1].Value = fa15 // Groups[0].Value = brother --- Groups[1].Value = bro16 // 結束輸出

這是其中一個樣本,匹配方法有三種: IsMatch(), Match(), Matches().

如果只是想知道"被匹配串"中是否包含某種"匹配模式", 可以使用IsMatch();

如果想得到一個匹配到的結果,可以使用Match();

如果想得到多個匹配到的結果,可以使用Matches();

單個匹配到的結果可以使用Groups[]擷取利用"匹配模式"匹配的分組,以便對匹配得到的資訊的利用。

 

 

具體使用規則:http://www.dotnetperls.com/regex-match

 

C#中Regex的簡單使用

聯繫我們

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