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));

            }



        }





    }





  

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值