1. 程式人生 > >C#中的正則表示式使用

C#中的正則表示式使用

最初它是在UNIX環境中開發的,與Perl一起使用得比較多。Microsoft把它移植到Windows中,到目前為止在指令碼語言中用得比較多。

注意,.NET正則表示式引擎是為相容Perl 5的正則表示式而設計的,但有一些新特性。

也就是說,.net遵守了perl的正則表示式規範,但是加入了自己的一些新特性。

很多書不會講如何使用,可能是1太簡單了,2已經有既定的標準了。

如果不是很熟悉,可以使用   MatchCollection matches = Regex.Matches()這個靜態方法。

using System;

using System.Collections;

using System.Linq;

using System.Text;

using System.Collections.Generic;

using System.Runtime.Serialization;

using System.Text.RegularExpressions;



namespace TestCS

{

 





    public class Progarm

    {

        public static void Main(string[] args)

        {

            string Text =

 @"anan ann This comprehensive compendium provides a broad and thorough investigation of all

aspects of programming with ASP.NET. Entirely revised and updated for the 2.0 

Release of .NET, this book will give you the information you need to master ASP.NET

and build a dynamic, successful, enterprise Web application.";



            string Pattern = @"s/b";



            MatchCollection matches = Regex.Matches(Text, Pattern, RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);





           ShowMatches(matches,Text);





            //組

            string groupPattern = @"(an)+";//將會找到 anan

            string groupPattern2 = @"an+"; //將會找到 ann

            MatchCollection matches2 = Regex.Matches(Text, groupPattern, RegexOptions.Multiline | RegexOptions.IgnoreCase);

            ShowMatches(matches2, Text);



            MatchCollection matches3 = Regex.Matches(Text, groupPattern2, RegexOptions.Multiline | RegexOptions.IgnoreCase);

            ShowMatches(matches3, Text);











        }
//顯示匹配到的左右5個字元



        private static void ShowMatches(MatchCollection matches,string text)

        {

            Console.WriteLine("Original text was: /n/n" + text + "/n");

            Console.WriteLine("No. of matches: " + matches.Count);

            foreach (Match nextMatch in matches)

            {

                int Index = nextMatch.Index;

                string result = nextMatch.ToString();

                int charsBefore = (Index < 5) ? Index : 5;

                int fromEnd = text.Length - Index - result.Length;

                int charsAfter = (fromEnd < 5) ? fromEnd : 5;

                int charsToDisplay = charsBefore + charsAfter + result.Length;



                Console.WriteLine("Index: {0}, /tString: {1}, /t{2}",

                   Index, result,

                   text.Substring(Index - charsBefore, charsToDisplay));

            }



        }





    }





  

}