正则表达式在.Net中的使用(C#)

来源:互联网 发布:商务酒店网络推广方案 编辑:程序博客网 时间:2024/05/22 22:25

.Net 框架内的三个主要处理正则表达式的类RegEx、Match和MatchCollection,这三个类都可以在System.Text.RegularExpressions命名空间下找到

==============================================================================

1.调用RegEx的IsMatch方法检查字符串是否与正则表达式匹配

       Regex objRegex;

       objRegex = new Regex( "正则表达式字符串" );

       bool result = objRegex.IsMatch( "需要匹配的字符串");

eg.        输出结果应为true,表匹配成功

Regex objRegex = new Regex("sophi[ae]");

      Response.Write(objRegex.IsMatch(
"sophia"));

 

==============================================================================

2.作为替换,也可以使用RegEx类的实例的Replace方法来匹配和替换字符串的一部分。

       Regex objRegEx = new Regex("正则表达式字符串");

       替换后的字符串 = objRegEx.Replace("需要替换的原字符串","用作替换的字符串");

eg.         输出结果为:sophi? is curious ?bout ?ll int?r?sting things.

Regex objRegEx = new Regex ("[ae]");

      
string strOrigin = "Sophia is curious about all interesting things."

       Response.Write(objRegEx.Replace(strOrigin,
"?");

 

==============================================================================

3.如果要添加由RegEx类所匹配的表达式的附加信息,那么就可以返回一个Match类的实例。

       RegEx objRegEx = new RegEx("正则表达式字符串");

       Match objMatch = objRegEx.Match("需要匹配的字符串");

       objMatch.Success    //类型bool 表示是否匹配成功

       objMatch.Index         //类型int  表示从字符串的第几个字符开始匹配(第一个字符的Index为0)

       objMatch.Length     //类型int  表示所匹配字符串的长度

       objMatch.Value       //类型string 表示所匹配字符串的值

eg.       输出结果为:Success:true

 RegEx objRegEx = new RegEx("eaw+");

       Match objMatch 
= objRegEx.Match("The mothod is easy.");

      Response.Write(
"Success:" + objMatch.Success+"<BR>");

      Response.Write(
"Index:" + objMatch.Index+"<BR>");

      Response.Write(
"Length:" + objMatch.Length+"<BR>");

      Response.Write(
"Value:" + objMatch.Value+"<BR>");

 

                               Index: 14

                               Length:4

                               Value:easy

==============================================================================

4.正则表达式可以匹配字符串的多个地方。如果找到多个匹配,可用MatchCollection来表示所有匹配。

        RegEx objRegEx = new RegEx("[正则表达式字符串");

        MatchCollection objMatchCollection = objRegEx.Match("需要匹配的字符串");

        foreach(Match objMatch in objMatchCollection)

              Response.Write("Value:"+objMatch.Value+"  ")

eg.      

RegEx objRegEx = new RegEx("[aeiou]")

   MatchCollection objMatchCollection 

   Response.Write("Value:"+objMatch.Value+"  ")
 
         foreach(Match objMatch in objMatchCollection)
= objRegEx.Match("Do you understand?");

        输出结果:Value:Do  Value:you  Value:understand

原创粉丝点击