C#Regex匹配相關字串__Regex

來源:互聯網
上載者:User
#Regex匹配字串的方法如下:


    1.使用C#中使用RegexSystem.Text.RegularExpressions命名空間;


    2.使用C#中使用RegexMatches()方法匹配字串,格式如下:
MatchCollection Matches = Regex.Matches(Str, Pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);


    其中Str表示輸入字串,Pattern表示匹配模式,RegexOptions.IgnoreCase表示忽略大小寫,RegexOptions.ExplicitCapture表示改變收集匹配方式。


    3.匹配結果儲存在MatchCollection集合中,可以通過迴圈遍曆結果集取出Match對象的結果。
TestRagular.cs:


using System;  
using System.Text.RegularExpressions;  
 
namespace Magci.Test.Strings  
{  
    public class TestRegular  
    {  
        public static void WriteMatches(string str, MatchCollection matches)  
        {  
            Console.WriteLine("\nString is : " + str);  
            Console.WriteLine("No. of matches : " + matches.Count);  
            foreach (Match nextMatch in matches)  
            {  
                //取出匹配字串和最多10個外圍字元  
                int Index = nextMatch.Index;  
                string result = nextMatch.ToString();  
                int charsBefore = (Index < 5) ? Index : 5;  
                int fromEnd = str.Length - Index - result.Length;  
                int charsAfter = (fromEnd < 5) ? fromEnd : 5;  
                int charsToDisplay = charsBefore + result.Length + charsAfter;  
 
                Console.WriteLine("Index: {0},\tString: {1},\t{2}", Index, result, str.Substring(Index - charsBefore, charsToDisplay));  
            }  
        }  
 
        public static void Main()  
        {  
            string Str = @"My name is Magci, for short mgc. I like c sharp!";  
 
            //尋找“gc”  
            string Pattern = "gc";  
            MatchCollection Matches = Regex.Matches(Str, Pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);  
 
            WriteMatches(Str, Matches);  
              
            //尋找以“m”開頭,“c”結尾的單詞  
            Pattern = @"\bm\S*c\b";  
            Matches = Regex.Matches(Str, Pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);  
 
            WriteMatches(Str, Matches);  
        }  
    }  

聯繫我們

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